Memory allocation Go is also garbage collected, meaning there is no need to worry about memory allocation and recycling. Go has two memory allocation primitives, new and make. They apply to different types, do different jobs, and may be confusing, but the rules are simple. 1. Allocating an in-memory built-in function with new new is essentially the same as the function of the same name in other languages: new (T) allocates 0 values to fill the memory space of type T, and returns its address, a value of type *t. In the terms of Go, it returns a pointer to the 0 value of the newly assigned type T. One thing is very important: new returns a pointer. This means that the user can create an instance of the data structure with new and can work directly. Type syncedbuffer struct {lock sync. Mutexbuffer bytes. The value of Buffer}syncedbuffer can be used immediately after allocating memory or definitions. In this fragment, both P and V can work without any further processing. P: = new (Syncedbuffer) ←type *syncedbuffer, can already use Var v syncedbuffer←type syncedbuffer, same as 2, use make to allocate memory built-in function m Ake (T, args) has different functions than new (t). It can only create slice,map and channel, and returns a T type with an initial value (not 0) instead of *t. Essentially, the reason that these three types are different is that references to data structures must be initialized before they are used. The difference between 3, new, and make for example, a slice is a three-item descriptor that contains pointers to data (internal array), length and capacity, and slice is nil until those items are initialized. For slice, map and Channel,make initialize the internal data structure and populate the appropriate values. Make returns the initialized (not 0) value. For example, make ([]int, 10, 100) allocates an array of 100 integers, and then creates a slice structure with length 10 and capacity 100 that points to the first 10 elements of the array. The difference is that new ([]int) returns a pointer to the newly allocated memory, while the slice structure of the 0 value padding is the slice value that points to nil. This example shows the difference between new and make. var p *[]int = new ([]iNT) ← Allocates slice structure memory; *p = = nil, already available var v []int = make ([]int,100) ←v points to a newly allocated array with 100 integers. var p *[]int = new ([]int) ← Unnecessary complex example *p = make ([]int, p, p) V: = yes ([]int, 100) ← More common Be sure to remember that do only applies to map,slice and Channel, and the return is not a pointer. A specific pointer should be obtained with new. New assignment; Make initialization above two paragraphs can be summed up briefly as:? New (T) returns *t points to a 0 value T? Make (t) returns the initialized T of course make only applies to Slice,map and channel. 4, constructors, and compound declarations sometimes a value of 0 does not satisfy the requirement, and there must be a constructor for initialization such as this example from the OS package. Func NewFile (fd int, name string) *file {if FD < 0 {return nil}f: = new (File) f.fd = Fdf.name = Namef.dirinfo = Nilf.nep Ipe = 0return F} has a lot of lengthy content. You can use compound declarations to make them more concise by creating a new instance with only one expression at a time. Func NewFile (fd int, name string) *file {if FD < 0 {return nil}f: = FILE{FD, name, Nil, 0}←create a new Filereturn &A Mp;f←return the address of F} returns the addresses of local variables without problems; After the function returns, the associated storage area still exists. In fact, getting an assigned instance from a composite declaration is better, so you can eventually shorten the two lines to one line. Return &FILE{FD, name, Nil, 0} in a particular case, if the composite declaration does not contain any fields, it creates a 0 value of a specific type. The expression new (File) and &file{} are equivalent. Compound declarations can also be used to create array,slice and maps, identifying fields by specifying the appropriate index and map keys. 12, define your own type 1, Go allows you to define a new type, implemented by the reserved word type: type foo int creates a new type Foo function like int. Creating more complex types requires the use of struct reserved words. Here's an example of recording someone's name (string) and age (int) in a data structure and making it a new type: Package Mainimport "FMT" type nameage struct {name string← do not export age int← does not export}func main () {A: = new (nameage) A.name = "Pete" a.age = 42fmt. Printf ("%v\n", a)} Usually, FMT. The output of Printf ("%v\n", a) is &{pete 42} If you want to print only one or a few of the fields in a structure, you need to use the. <field name>. For example, just print the name: FMT. Printf ("%s", A.name) ←%s the formatting of the string 2, the structure field before the project referred to in the structure is called field. There is no structure for a field: struct {} has four fields: struct {x, y IntA *[]int F func ()} If you omit the name of the field, you can create an anonymous field, for example: struct {t1← field name is t1*t2← field name is T2P. t3← field name is t3x,y int← field name is x and y} note the first letter of the field can be exported, that is, in other packages can be read and write. The field name starts with a lowercase letter and is private to the current package. The function definition of the package is similar. The 3 method can create a function for the newly defined type to operate, which can be done in two ways: 1. Create a function to accept parameters of this type. Func dosomething (in1 *nameage, in2 int) {/* ... */} (as you might have guessed) this is a function call. 2. Create a function that works on this type: func (in1 *nameage) dosomething (in2 int) {/* ... */} This is a method call and can be used like this: Var n *nameagen.dosomething (2) here Go looks for a list of methods of variable N of type Nameage, finds a list of methods for the *nameage type without finding it, and converts it to (&n). DoSOmething (2). Using a function or method is entirely up to the programmer, but the method must be used if the interface needs to be met. If there is no such requirement, then it is entirely up to the habit to decide whether to use the function or the method. If x can get an address, and &x's method contains M, X.M () is (&x). m () a shorter notation. 14, conversion 1, sometimes you need to convert one type to another type. You can do it in Go, but there are some rules. First, converting one value to another is done by the operator (which looks like a function: Byte ()), and not all conversions are allowed. Slice from string to byte or ruin. MyString: = "Hello this is string" byteslice: = []byte (mystring) converted to byte slice, each byte holds the integer value of the byte corresponding to the string. Note that the Go string is UTF-8 encoded, and some characters may be 1, 2, 3, or 4 bytes end. Runeslice: = []rune (mystring) converts to Rune slice, each rune holds a Unicode encoded pointer. Each character in the string corresponds to an integer. From a byte or slice to a string. B: = []byte{' h ', ' e ', ' l ', ' l ', ' o '}← compound declaration s: = string (b) I: = []rune{257,1024,65}r: = string (i) for numeric values, the following conversion is defined:? Converts an integer to the specified (bit) length: uint8 (int);? From floating-point numbers to integers: Int (float32). This truncates the decimal part of the floating-point number; Similar to other: float32 (int). 2, how does the conversion of a user-defined type convert between custom types? There are two types of Foo and bar created, and Bar is an alias for foo: type foo struct {int}← anonymous field type Bar foo←b AR is the alias of Foo and then: var b bar=bar{1}← Declaration B is bar type var f foo=b← assignment B to f the last line causes an error: cannot use B (type bar) as type Foo in Assi Gnment (Cannot use B (type bar) as the Type Foo Assignment) This can beTo fix by conversion: var f foo = foo (b) It is quite difficult to change the structure of those fields that are inconsistent. Also note that converting B to int will also make an error, and that integers are not the same as the structure with integer fields.
Go Language Basics (v) Advanced