//=== class ?
http://www.golangpatterns.info/object-oriented/classes
type Integer int;
func (i *Integer) String() string {
return strconv.itoa(i)
}
--> Integer is a 'class'[type] with member method String()
//=== struct
https://golang.org/ref/spec#Struct_types
"""...
A struct is a sequence of named elements, called fields, each of which has a name and a type
// An empty struct.
struct {}
// A struct with 6 fields.
struct {
x, y int
u float32
_ float32 // padding
A *[]int
F func()
}
A field declared with a type but no explicit field name is an anonymous field
..."""
//=== address operators : & and *
https://golang.org/ref/spec#Operators
& :
For an operand x of type T, the address operation &x generates a pointer of type *T to x.
* :
For an operand x of pointer type *T, the pointer indirection *x denotes the variable of type T pointed to by x
//=== constructor?
http://ww.golangpatterns.info/object-oriented/constructors
Go has no 'real' constructors
--> but 'constructor-like' factory function
"""...
package matrix
function NewMatrix(rows, cols int) *matrix {
m := new(matrix)
m.rows = rows
m.cols = cols
m.elems = make([]float, rows*cols)
return m
}
To prevent users from instantiating uninitialized objects,
the struct can be made private.
package main
import "matrix"
wrong := new(matrix.matrix) // will NOT compile (matrix is private)
right := matrix.NewMatrix(2,3) // ONLY way to instantiate a matrix
...
matrix := NewMatrix(10, 10)
pair := &Pair{"one", 1}
...
function NewMatrix(rows, cols, int) *matrix {
return &matrix{rows, cols, make([]float, rows*cols)}
}
http://stackoverflow.com/questions/6420734/in-go-how-do-i-create-a-constructor-for-a-type-with-a-string-base-type
type Client struct {
// ...
}
func NewClient() *Client {
return &Client{/* ... */}
}
..."""
//=== new(Type) vs &Type{...} , new(T) and &T{}
https://groups.google.com/forum/#!topic/golang-nuts/9qHAbDDhuqY
https://groups.google.com/forum/#!topic/golang-nuts/FPrkMS2EgoY
http://stackoverflow.com/questions/13244947/is-there-a-difference-between-new-and-regular-allocation
to allocate memory space for an object of 'composite' type T with zero-initial values
--> new T() or &T{}
&T{} doesn't work for basic types,
it is only permitted when T is a struct, array, slice, or map type.
can write "p := new(int)" but can't write "p := &int{0}"
If you want to allocate a pointer,
new(*T) (which returns a **T) is the only way
2015年3月30日 星期一
golang class and constructor?
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言