go基础语法的一些东西

map

1
2
3
4
5
6
7
8
9
foo := make(map[string]int)
foo["bar"] = 42

// To delete an item from a map, you can use
delete(foo, "bar")

value, exists := foo["baz"]
// If the key "baz" does not exist,
// value: 0; exists: false

Note that slices and maps are exceptions to the above-mentioned rule. When we pass a slice or a map as arguments into a function, they are treated as pointer types even though there is no explicit * in the type. This means that if we pass a slice or map into a function and modify its underlying data, the changes will be reflected on the original slice or map.

struct

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
You can create an instance of a struct without using the field names, as long as you define the fields in order:

type Shape struct {
    name string
    size int
}

s := Shape {
	"Oval",
	20,
}

new

1
2
3
4
5
6
7
8
9
func NewShape(name string) Shape {
    return Shape{
        name: name,
        size: 100, //default-value for size is 100
    }
}

NewShape("Triangle")
// => Shape { name: "Triangle", size: 100 }
  • validation of the given values
  • handling of default-values
  • since New functions are often declared in the same package of the structs they initialize, they can initialize even private fields of the struct

method

pointer receivers.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
type rect struct {
width, height int
}
func (r \*rect) squareIt() {
r.height = r.width
}

r := rect{width: 10, height: 20}
fmt.Printf("Width: %d, Height: %d\n", r.width, r.height)
// Output: Width: 10, Height: 20

r.squareIt()
fmt.Printf("Width: %d, Height: %d\n", r.width, r.height)
// Output: Width: 10, Height: 10

ref

  1. exercism