05. Composite Types
If the values of a type T can be represented with composite literals, then T{} is its zero value. Справедливо для struct, slice.
Golang
Classic OOP
struct
class with fields, only non-virtual methods
interface
class without fields, only virtual methods
embedding
multiple inheritance AND composition
receiver
implicit this parameter
new expression
new expressionGo has two allocation primitives, the built-in functions new and make.
The built-in function new takes a type T, allocates storage for a variable of that type at run time, but unlike its namesakes in some other languages it does not initialize the memory, it only zeros it. That is, new(T) allocates zeroed storage for a new item of type T and returns its address, a value of type *T. In Go terminology, it returns a pointer to a newly allocated zero value of type T.
new(Type) *TypeFor instance:
type S struct { a int; b float64 }
new(S)allocates storage for a variable of type S, initializes it (a=0, b=0.0), and returns a value of type *S containing the address of the location.
make function
make functionThe built-in function make(T, args) creates slices, maps, and channels only, and it returns an initialized (not zeroed) value of type T (not *T).
The reason for the distinction between new and make is that these three types represent, under the covers, references to data structures that must be initialized before use. A slice, for example, is a three-item descriptor containing a pointer to the data (inside an array), the length, and the capacity, and until those items are initialized, the slice is nil. For slices, maps, and channels, make initializes the internal data structure and prepares the value for use.
var p *[]int = new([]int) // allocates slice structure; *p == nil; rarely useful
var v []int = make([]int, 100) // the slice v now refers to a new array of 100 intsI found make and new very interesting and hence decided to list down the differences between new and make:
new---> returns pointermake---> returns an initialized value of type Tnew---> initializes to 0 value of the typemake---> does not initialize to 0 value of the typenew---> used for all typesmake---> used for only slices, maps and channels
Last updated
Was this helpful?