Skip to content

Instantly share code, notes, and snippets.

@afreeland
Created April 5, 2018 12:51
Show Gist options
  • Save afreeland/fc0b2624f42117fd238c457854867859 to your computer and use it in GitHub Desktop.
Save afreeland/fc0b2624f42117fd238c457854867859 to your computer and use it in GitHub Desktop.
Go: basic structs
package main
import (
"fmt"
)
func main() {
// We created two structs in the local execution stack...its better to do large objects in heap
foo := myStruct{}
foo.myField = "bar"
fmt.Println(foo.myField)
// Instantiate with data...must be in the order the fields are in the struct
baz := myStruct{"bar"}
fmt.Println(baz.myField)
// Creating on the heap using new()
test := new(myStruct)
test.myField = "bar"
fmt.Println(test.myField)
// test is a memory address...however you do not need to dereference since Go's compiler will dereference if it feels its a pointer
println(test)
// Reference type
// & => Allows us to use our literal syntax again
test2 := &myStruct{"bar"}
fmt.Println(test2.myField)
fmt.Println(test2)
// Go keeps track of our variable, Go will not Garbage Collect it
}
type myStruct struct {
myField string
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment