Golang - Types
Similar to C/C++, you can declare custom types :
1
2
3
| type Tuple struct {
X, Y, Z, W float64
}
|
You can also declare an alias to a type:
1
2
3
| type Foo String
var bar Foo = "FooString"
|
However, it is essential to note that Foo and string are now two different types. Since 1.9, you are able to tell the compiler that a type alias is just another name but should be considered the same type overall.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| type Tuple struct {
X, Y, Z, W float64
}
type Point = Tuple
type Vector = Tuple
func NewTuple(x, y, z, w float64) *Tuple {
t := new(Tuple)
t.X = x
t.Y = y
t.Z = z
t.W = w
return t
}
func NewPoint(x, y, z float64) *Point {
return NewTuple(x, y, z, 0)
}
func NewVector(x, y, z float64) *Vector {
return NewTuple(x, y, z, 1)
}
|
Structs can be declared on the fly, bound to the current scope:
1
2
3
4
5
6
7
8
9
| func foo(){
type Bar {
baz String
}
s := Bar{ baz: "I like trains" }
...
}
|
You can also define structs inline with an assignment and assign values at the same time:
1
2
3
4
5
6
7
8
9
10
11
| func foo() {
m := map[string]struct {
Foo int
}{
"keyA" : { Foo: 1},
"keyB" : { Foo: 2},
}
}
|