LoginSignup
1
1

More than 5 years have passed since last update.

tour of go メモ

Last updated at Posted at 2015-07-18

Struct Literals

type Vertex struct {
    X, Y int
}

var (
    v1 = Vertex{1, 2}  // has type Vertex
    v2 = Vertex{X: 1}  // Y:0 is implicit
    v3 = Vertex{}      // X:0 and Y:0
    p  = &Vertex{1, 2} // has type *Vertex
)

func main() {
    fmt.Println(v1, p, v2, v3)
}

v1 = Vertex{1, 2} と p = &Vertex{1, 2} の違い。

If you say
p := Vertex{1,2}

Then you create a new Vertex structure and assign it to the variable p. p has type Vertex.

If you do
q := &Vertex{1,2}

create a new Vertex structure, take a reference to it, and assign that reference to q.
q has type *Vertex.

Just like having a Vertex and a pointer to a vertex are different, so is doing Vertex{1,2} and &Vertex{1,2}

go-lang nuts より

Array,Map関係

array

Go's arrays are values....This means that when you assign or pass around an array value you will make a copy of its contents...

One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.
b := [2]string{"Penn", "Teller"}

var [4]int -> [int] [int] [int] [int]
http://blog.golang.org/

slice

Arrays..are a bit inflexible,..Slices, though, are everywhere. They build on arrays to provide great power and convenience.

letters := []string{"a", "b", "c", "d"}

A slice can be created with ...make. The make function takes a type, a length, and an optional capacity.
len -> length
cap -> capacity

var s []byte
s = make([]byte, 5, 5)
// s == []byte{0, 0, 0, 0, 0}

Capacity and Length

Cap -> length of underlying array.
Len -> length of array.


func main() {
    elements := []int{100, 200, 300}

    // Capacity is now 3.
    fmt.Println(cap(elements))

    // Append another element to the slice.
    elements = append(elements, 400)

    // Capacity is now 6—it has doubled.
    fmt.Println(cap(elements))

    // Create an empty slice.
    // ... Its length is 0.
    items := []string{}
    fmt.Println(len(items))

    // Append a string and the slice now has a length of 1.
    items = append(items, "cat")
    fmt.Println(len(items))

}
http://www.dotnetperls.com/

append

test_array - []string{}

GO: append(test_array, "x", "y", "z")
-> Ruby: test_array << ["x", "y", "z"]

range and iteration

The range keyword is used with a for-loop. When we use range on a slice, all the indexes in the slice are enumerated.

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    for index, value := range pow {
        fmt.Println(index, value)
    }
    for _, value := range pow {
        fmt.Println(value)
    }
    for index, _ := range pow {
        fmt.Println(index)
          fmt.Println(index, _) // -> !!エラー!!
    }
}

1
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1