I've finished watching the "Pointer" edition of the udemy course, so I'll summarize and look back.
This time as well, I learned the basic operation while outputting on the console.
・ Learn Go by watching [Introduction to Go taught by active Silicon Valley engineers + Development of Bitcoin Systre Fintech app by application]](https://www.udemy.com/course/go-fintech/) on udemy During ~
・ Development environment is VS Code + plug-in (Go version is 1.15) ・ OS is Windows ・ I usually use Java.
-If you specify a pointer type variable, you can directly overwrite the contents of the memory. ・ If it is difficult to understand, add "&" and "*" and move it appropriately to understand. -When generating a pointer type, use "new" instead of "make".
python
func one(x int) {
//Receive only values from the main function
fmt.Println(&x)
x = 1
}
func two(x *int) {
//Receives the address of x in a pointer-type box.
fmt.Println(&x)
//Overwrite the contents of the address directly
*x = 2
}
func main() {
var n int = 100
//Memory address is output
fmt.Println(&n)
//Integer point type address is entered (same as C language)
var p *int = &n
fmt.Println(p)
//When you want to see the contents of the memory pointed to by the address
fmt.Println(*p)
one(n)
//Since n in the argument of one is a copy, it has no effect on n in the function.
fmt.Println(n) //100 is output
two(&n)
fmt.Println(n) //2 is output
}
I couldn't understand this "pointer", but the article "Pointers and addresses learned with Go" and the links quoted in the articles. The explanation above was easy to understand. Since it is a concept derived from C language, it seems that there is knowledge that many seniors have struggled to accumulate.
-A structure can be defined with "
python
type Vertex struct {
//Variable starts with a capital letter
//Treated as private when made lowercase
X int
Y int
S string
}
func changeVertex(v Vertex) {
v.X = 1000
}
func changeVertex2(v *Vertex) {
v.X = 1000
(*v).X = 1000 //This is the correct way to write it, but in the case of struct, it automatically refers to the actual pointer.
}
func prg3() {
//Structure generation
v := Vertex{X: 1, Y: 2} //Initial values are entered for variables that are not defined
changeVertex(v) //Pass the structure by value (copy)
fmt.Println(v) //Output result:{1 2 }
v.X = 100 //Variables can also be specified
fmt.Println(v.X, v.Y) //Output result: 100 2
v2 := &Vertex{1, 2, "text"}
changeVertex2(v2)
fmt.Println(v2) //Output result:&{1000 2 text}
var v3 Vertex
fmt.Println(v3) //Note that it is not nil. The one with the initial value is constructed
//Output result:{0 0 }
v4 := new(Vertex)
fmt.Println(v4) //Pointer type output result:&{0 0 }
v5 := &Vertex{}
fmt.Println(v5) //It has the same contents as the pointer type v6, but it is easier to distinguish it from the pointer type.
}
・ It is difficult to understand the concept of pointers. -The struct feels like a java object.
Last post
Recommended Posts