Custom Type and Receiver
define a type
type deck []string
receiver
fun (d deck) print() {
for i, card := range d {
fmt.Printf(i, card)
}
}
call print func
d := deck{"card1", "card2"}
d.print()
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")
}
Structs
define a struct
type person struct {
firstName string
lastName string
}
declare a struct
// alex := person{"Alex", "Anderson"} //rely on order.
alex := person{firstName: "Alex", lastName: "Anderson"}
alex.firstName = "Alex"
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.
Top comments (0)