This is a creation in Article, where the information may have evolved or changed. Go has pointers, but there is no pointer operation. You cannot traverse the individual bytes of a string with a pointer variable.Define a pointer ' * ' by type as a prefix: var p *int. P is now a pointer to an integer value. All newly defined variables are assigned a value of 0 of their type, and the pointers are the same. A new defined or no pointer to the value nil. In other languages, this is often called the null (NULL) pointer, which is nil in go. Let the pointer point to something, you can use the Fetch operator (&)
If receiver of a method is *t, you can call this method on an instance variable V of type T, without needing &v to call this method similar if the receiver of a method is T, you can The variable p of type T calls this method, and does not need *p to call this method
Example 1:package mainimport "FMT" Func Main () {var p *int fmt. Printf ("%v\n", p) var i int p = &i FMT. Printf ("%v\n", p)}
Output Result: <nil>0x18600118
Example 2:package mainimport "FMT" Func Main () {var p *int var i int p = &i *p = 8 FMT. Printf ("%v\n", *p) fmt. Printf ("%v\n", i)} Output results: 88
Because go does not have pointer arithmetic, if you write this: *p++, it means (*p) + +: First get the value pointed to by the pointer, and then add one to this value.
Go has two memory allocation primitives, new and make
1. Allocating memory with new it returns a pointer to the 0 value of the newly assigned type T.
2. Use make to allocate memory built-in functions make (T, args) have 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.
New (t) returns *t pointing to a 0 value Tmake (t) returning the initialized T
define your own typeGo allows you to define a new type, implemented with 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.
Example: Package Mainimport "FMT" type nameage struct {name string//Do not export age int//Do not export}func main () {a : = new (nameage) A.name = "Pete" a.age = fmt. Printf ("%v\n", a) fmt. Printf ("%v\n", A.name)} output result: &{pete 42}pete
Note that the first uppercase fields in struct{} can be exported, that is, they can be read and written in other packages. The field name begins with a lowercase caption that is private to the current package.
Example 2:
type person struct { name string age int}var P person // P现在就是person类型的变量了P.name = "Astaxie" // 赋值"Astaxie"给P的name属性.P.age = 25 // 赋值"25"给变量P的age属性fmt.Printf("The person's name is %s", P.name) // 访问P的name属性.
In addition to the above statement use of P, there are two ways to use the Declaration
1. Provide initialization values in order
p: = person{" Tom ", +-
2. field:value
initialize in a way that can be in any order
P: = person{age:24, Name: "Tom"}
Example 3:package mainimport "FMT"
Declares a new type, person struct {name, string age int}
Compare the age of two people, return to the older person, and return the age difference//Note: The struct is also the value of the Func older (P1, p2 person) (person, int) {if p1.age>p2.age {//compare P1 and P2 The age of these two people return P1, p1.age-p2.age} return P2, p2.age-p1.age}
Func main () {var tom person//Assignment initialization tom.name, tom.age = "Tom", 18
Two fields are written with a clear initialization bob: = person{age:25, Name: "Bob"}
Initialize values in the order of struct definitions paul: = person{"Paul", 43}
Tb_older, Tb_diff: = older (Tom, Bob) Tp_older, Tp_diff: = older (Tom, Paul) Bp_older, Bp_diff: = older (Bob, Paul)
Fmt. Printf ("of%s and%s,%s is older by%d years\n", Tom.name, Bob.name, Tb_older.name, Tb_diff)
Fmt. Printf ("of%s and%s,%s is older by%d years\n", Tom.name, Paul.name, Tp_older.name, Tp_diff)
Fmt. Printf ("of%s and%s,%s is older by%d years\n", Bob.name, Paul.name, Bp_older.name, Bp_diff)} output results: Of Tom and Bob, Bob is older by 7 Yearsof Tom and Paul, Paul was older by Yearsof Bob and Paul, Paul was older by
anonymous fields for structs
We have described how to define a struct, defined by a field name corresponding to its type one by one, and in fact go supports providing only the type, not the way to write the field name, that is, anonymous fields, also known as embedded fields. When the anonymous field is a struct, all the fields owned by the struct are implicitly introduced to the currently defined struct.
Example: Package Mainimport "FMT"
Type Human struct {name string age int Weight int}
Type Student struct { HumanAnonymous field, the default student contains all fields of human speciality string}
Func Main () {//We initialize a student mark: = student{human{"Mark", [+], "Computer Science"}
We access the corresponding fields in FMT. Println ("His name is", Mark.name) fmt. Println ("His was", Mark.age) fmt. Println ("He weight is", mark.weight) fmt. Println ("He speciality is", mark.speciality)//Modify the corresponding memo information mark.speciality = "AI" FMT. Println ("Mark changed his speciality") fmt. Println ("He speciality is", mark.speciality)//Modify his age information fmt. Println ("Mark become old") Mark.age = Fmt. Println ("He is", mark.age)//Modify his weight information fmt. Println ("Mark is not a athlet anymore") mark.weight + =-FMT. Println ("He weight is", mark.weight)} output: His name was Markhis age is 25His weight was 120His speciality is computer Sc Iencemark changed his specialityhis speciality be aimark become oldhis age was 46Mark is not a athlet anymorehis weight I S 180
MethodThe new defined type can be used to create the first function for operation, 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 (see receiver defined in 3.1): func (in1 *nameage) dosomething (in2 int) {/* ... */} This is Method Invocation, can be used like this: var n *nameage n.dosomething (2)
Example 1:package mainimport "FMT" type nameage struct {name string Age Int}func main () {A: = new (nameage) A.name = " Pete "a.age = DoSomething (A, 3)}func dosomething (in1 *nameage, in2 int) {FMT. Printf ("%v\n", In1.name) fmt. Printf ("%d\n", in2)} output Result: Pete3
Example 2:package mainimport "FMT" type nameage struct {name string Age Int}func main () {A: = new (nameage) A.name = " Pete "a.age = a.dosomething (333)}func (in1 *nameage) dosomething (in2 int) {FMT. Printf ("%v\n", In1.name) fmt. Printf ("%d\n", in2)} output Result: Pete333
Type ConversionsSometimes a type needs to be converted to another type. You can do it in go, but there are some rules.
Note that the go string is UTF-8 encoded, and some characters may be 1, 2, 3, or 4 bytes end.
Example: Package Mainimport "FMT" Func Main () {mystring: = ' Hello world ' byteslice: = []byte (mystring) For _, Val: = Rang E byteslice {fmt. Printf ("%v\n", Val)}} output Result: 10410110810811132119111114108100
Example 2package mainimport "FMT" Func Main () {mystring: = ' Hello world ' byteslice: = []rune (mystring) For _, Val: = Rang E byteslice {fmt. Printf ("%c\n", Val)}} output Result: Hello
World for numeric values, the following conversions are 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; • Other similar: float32 (int). Example: Package Mainimport "FMT" Func Main () {myfloat: = 123.72 Myint: = Int (myfloat) fmt. Printf ("%.3f\n", Myfloat) fmt. Printf ("%d\n", Myint)} Output results: 123.720123
conversion of user-defined typesHow do I convert between custom types? Two types of Foo and bar are created here, and Bar is an alias for foo: type foo struct {int} anonymous field type Bar foo Bar is an alias of Foo and then: var b bar = bar{1} Declaration b is BA R type var f foo = b Assignment B to f the last line will cause an error: cannot use B (type bar) as type Foo in assignment (can not be assigned as type Foo using B (types bar) This can be fixed by conversion: VA R 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.
Example: Package Mainimport "FMT" type foo struct {int}//anonymous field type Bar Foofunc main () {b: = bar{1}//Declaration B is the bar type, and the initial value var f foo = b//above is assigned a value B to f, which causes a line error cannot use B (type bar) as type Foo in assignment (cannot be used B (type bar) as the type Foo Assignment) var f foo = foo (b)//This is possible with FMT. Printf ("%d\n", f)} output Result: {1}
Note: converting B to int also makes an error, and integers are not the same as the structure with integer fields.