This is a creation in Article, where the information may have evolved or changed.
This document is the go language of those pits two.
The function in Golang is considered a value, the function value can not be compared, nor can it be a key of the map
Can the following code compile and pass?
12345678910111213 |
import (" FMT ") func Span class= "title" >main {array: = make ( span class= "keyword" >map [int ] Func () int ) array [func () int {return 10 } ()] = func () int {return 12 } Fmt. Println (Array)} |
Answer:
1 |
can be compiled correctly. |
A little change, instead of the following, can you compile and pass?
1234567891011 |
Import ("FMT") funcmain() Make (map[func()int]int) Array [func()int{return: FMT. Println (Array)} |
Answer:
1 |
Cannot compile through. |
In the go language, a function is considered to be the first class of values: (first-class values): functions, like other values, can be assigned, passed to a function, and returned from a function. can also be used as a "function type". For example, if you have a function func square(n int) int { return n * n }
, you can assign a value f := square
, and you can fmt.Println(f(3))
(print out "9").
The Go language function has two unique points:
- Function value type cannot be a key for map
- There is no comparison between the function values, the function value can only be compared with nil, and the 0 value of the function type is
nil
anonymous function Scope traps
See what the following code outputs?
123456789101112131415161718192021 |
import () Func main () {var msgs []func () Span class= "title" >array : = []string { "1" , "2" , , ,} _, E: = range array{msgs = append (msgs, func () {fmt.
Println (e)})}for _, V: = range msgs{v ()}} |
Answer:
In the above code, the memory address of the loop variable is recorded in the anonymous function, not the value of the loop variable at some point in time.
To Output 1, 2, 3, 4 you need to change to:
123456789101112131415161718192021 |
Import () func main () {var msgs []func () Array : = []string {, "2" , , ,}for _, E: = range array{elem: = EMSGS = append (msgs, func () {fmt.
Println (Elem)})}for _, V: = range msgs{v ()}} |
In fact, add a elem := e
seemingly redundant, in fact, so, each time after the loop each anonymous function is stored in the local variable elem
value, such a local variable defined 4, each cycle generated one.
[3]int
and [4]int
does not count the same type
Please take a look at the code, can I ask the output true
orfalse
12345678910 |
Import ( "FMT" "reflect")funcmain(){ Arraya: = [ ...] int {123} Arrayb: = [...] int {1234} Fmt. Println (reflect. TypeOf (Arraya) = = reflect. TypeOf (Arrayb))} |
The answer is:
The array length is an integral part of the array type, so [3]int and [4]int are two different types of arrays.
Arrays can also be initialized by specifying an index and corresponding values.
For example:
12345678 |
Import ( "FMT")funcmain(){ Arraya: = [...] int {0:12:13:4} Fmt. Println (Arraya)} |
Will output:
It's kind of like PHP
an array, but it's different: arrayA
How long is it?
12345678 |
Import ( "FMT")funcmain(){ Arraya: = [...] int {0:12:13:4} Fmt. Println (len(Arraya))} |
The answer is:
Yes, an array with an array length of 4 is defined, the array length of the specified index is related to the value of the last index, for example: an r := [...]int{99:-1}
array with 100 elements is defined r
, the last element is output to 1, and the other elements are initialized with 0.
Cannot take address action on an element in map &
1 |
A: = &ages["Bob"//compile Error:cannot take address of Map element |
The element in map is not a variable, it is not possible to take an address operation on the map element, and the reason for not taking an address to the map may be that map may reallocate memory space as the element is added, which will cause the original address to be invalid
You cannot add a value when map is nil
12345 |
func Main () { varmap[string]int samplemap["test" 1 Fmt. Println (Samplemap)} |
Output error:
1 |
Panic:assignment to entry in nil map |
You must use make or initialize the map before you can add elements.
The above code can be changed to:
12345678 |
func Main () { varmap[string]int map[string ]int { "test1":1, } samplemap["Test"1 FMT. Println (Samplemap)} |
can be output correctly:
&dilbert.Position
and (&dilbert).Position
it's different.
&dilbert.Position
Equivalent &(dilbert.Position)
rather than(&dilbert).Position
Take a look at the example:
What is the output, please?
123456789101112131415161718 |
func Main (){ typestruct { int string string DoB time. Time string int int } var Dilbert Employee "123" Position: = &dilbert. Position FMT. Println (position)} |
Output:
The output is the memory address
Revise it and change it to &dilbert.Position
(&dilbert).Position
123456789101112131415161718 |
func Main (){ typestruct { int string string DoB time. Time string int int } var Dilbert Employee "123" Position: = &dilbert. Position FMT. Println (position)} |
Output:
When a function returns a value in the go language, it cannot be assigned a value
Take a look at the following example:
1234567891011121314151617 |
type Employee struct {ID int Name
string Address
string DoB time. Time Position
string Salary
int managerid
int }
func employeebyid (ID int ) employee {
return employee{id:id}}
func main () {Employeebyid (
1 ). Salary =
0 }
|
Can I compile and pass it?
operation, output error:cannot assign to EmployeeByID(1).Salary
In this example, the function EmployeeById(id int)
returns a value type, and its value is EmployeeByID(1).Salary
a value type; What is the concept of a value type? A value type is var a = 1
a concept that is to the right of an assignment statement or an equal sign, and is var a = hello world
=
1
Hello world
not assignable, only the variable can be assigned value.
Modify the program as follows:
123456789101112131415161718 |
Type Employee struct {ID int Name string Address string DoB time. Time Position string Salary int managerid int }func employeebyid (ID int ) employee {return employee{id:id}}func main () {var a = Employeebyid (1 ) a.salary = 0 } |
This can be compiled and passed.
When declaring a method, it is not allowed to appear in a method's sink if a type name is itself a pointer
Please see the following example, would you like to compile the pass?
123456789101112131415161718192021 |
span class= "keyword" >import ( "FMT" ) type Littlegirl struct {Name string age }type girl *littlegirlfunc changename (name span class= "keyword" >string ) {this. Name = Name}func main () {littlegirl: = Girl{name: "Rose" , Age:1 }girl.changename () fmt. Println (Littlegirl)} |
Answer:
1 |
Cannot compile through, will prompt "Invalid receiver type girl (girl is a pointer type)" |
The go language states that only types (type) and pointers to them (*type) are the two receivers that may appear in the receiver declaration, in order to avoid ambiguity, it is expressly stated that a type name is not allowed in the receiver if it is itself a pointer.
The function allows the nil pointer as a parameter, and also allows the receiver to use nil as the method
Please look at the following example, can I compile and pass it?
123456789101112131415161718192021 |
Import ("FMT") type struct string int} func(this littlegirl)changenamestring) {FMT. PRINTLN (name)}funcmain(){little: = Littlegirl{name:"Rose" , Age:1nillittle.changename ("Yoyo") fmt. Println (Little)} |
Answer:
1 |
Cannot compile through, display "cannot using nil as type Littlegirl in assignment" |
In the Go language, the Allow method uses the nil pointer as its receiver, and it allows the function to use the nil pointer as a parameter. Instead of the pointer type in the above code, the littleGirl
*littleGirl
variable is then little
assigned to &littleGirl{Name:"Rose", Age:1}
be compiled and passed.
Also, nil is a valid 0 value for the object, such as map or slice, which can be compiled and run normally.