package main import "fmt" // Pass by reference func print_array(ary []int) { for _, v := range ary { fmt.Printf("%d\n", v); } } func main() { // Declaring own type. type T struct { id int; name string } var b T; b.id = 1; b.name = "foo"; // Use new to create pointer. t := new(T); // var t *T = new(T); t.id = 2; t.name = "bar"; fmt.Printf("%d: %s\n", t.id, t.name); // An array is values. var ary [10]int; for i := 0; i < len(ary); i++ { ary[i] = i; } print_array(&ary); // pass pointer to get slice. // Can use new to create a pointer to an array. ary2 := new([10]int); for i := 0; i < len(*ary2); i++ { (*ary2)[i] = i; } for _, v := range *ary2 { fmt.Printf("%d\n", v); } // The map is a reference type (so are slice and channel), // and built by make. m := make(map[string]int); m["a"] = 1; m["b"] = 2; fmt.Printf("%d\n", m["b"]); }
Type exercise for go language
Tags: