DEV Community

jguo
jguo

Posted on

1

Learning Golang 105

Custom Type and Receiver

define a type

type deck []string
Enter fullscreen mode Exit fullscreen mode

receiver

fun (d deck) print() {
   for i, card := range d {
     fmt.Printf(i, card)
   }
}
Enter fullscreen mode Exit fullscreen mode

call print func

d := deck{"card1", "card2"}
d.print()
Enter fullscreen mode Exit fullscreen mode

You can see that adding a receiver to a custom type, it extends the type's functionality.

Type assertions

A type assertion takes an interface value and extracts from it a value of the specified explicit type.
For example

res, ok := deck.([]string)
if ok {
    fmt.Printf("slice value is: %q\n", res)
} else {
    fmt.Printf("value is not a slice\n")
}
Enter fullscreen mode Exit fullscreen mode

Structs

define a struct

type person struct {
  firstName string
  lastName  string
}
Enter fullscreen mode Exit fullscreen mode

declare a struct

// alex := person{"Alex", "Anderson"} //rely on order.
alex := person{firstName: "Alex", lastName: "Anderson"}
alex.firstName = "Alex"

Enter fullscreen mode Exit fullscreen mode

Pointers

Go passes by value. It creates a copy when you pass a value.
& give the address of a value
* give the value of an address or define a pointer.

Turn address into value with *address.
Turn value into address with &value.

Value Types Reference Types
int slices
float maps
string channels
bool points
structs functions

when passing a reference type, go still make a copy, but reference type is a reference. So, it is like passing by reference.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)