I didn't know what the pointer was, so I looked it up. This time I wrote it in Go.
pointer_practice.go
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
x := 2
/*Address of variable x(The location of the memory where the variable x is stored)Store*/
/*A variable that stores the address of a variable is called a pointer variable.*/
x_pointer := &x
fmt.Println(x)
fmt.Println(x_pointer)
/*Pointer variable x_Get the value that exists at the address stored in pointer*/
/*If you think of memory as a js object and address as an object key, memory[address(x_pointer)] =Image of 2*/
fmt.Println(*x_pointer)
arg := 0
arg_pointer := &arg
test_pointer(arg_pointer)
/*Same result*/
fmt.Println(arg)
fmt.Println(*arg_pointer)
/*Value cannot be rewritten(It can be rewritten in the function, but it does not affect the value of the variable set as an argument.) */
/*Get the rewrite result in the function with return*/
test_val(arg)
fmt.Println(arg)
}
/*A function that takes a pointer variable as an argument(Pass by pointer) */
func test_pointer(val_pointer *int) {
/*Seed using time(Source of random numbers?)I get the same value every time without Seed*/
rand.Seed(time.Now().UnixNano())
/*Get the address stored in the pointer variable->Specify the location of the memory to rewrite the value by address->0 the value stored in the specified memory location~Rewrite to a random number of 999*/
*val_pointer = rand.Intn(1000)
}
/*Value-passing function(The usual) */
func test_val(val int) {
rand.Seed(time.Now().UnixNano())
val = rand.Intn(1000)
}
The method of setting the argument type differs between the function that passes by value (receives the value of a variable) and the function that passes by a pointer (receives the address of a variable).
/*Value-passing function*/
func(Argument Argument type) { /*Function processing*/ }
/*Before the function type name passed by pointer, "*Is attached*/
func(argument*Argument type) { /*Function processing*/ }
Recommended Posts