When I was studying Go, I rediscovered (or rather reviewed) it, and I realized that the basics were missing. I think I learned it when I studied C language, but I'm completely out of my mind, so I'll write it down. In this article, C and Go are used as examples.
First, let's pass the value of the variable to the function normally.
#include<stdio.h>
int plus1(int x){
x = x + 1 ;
return x ;
}
int main(void){
int a ;
a = 1 ;
plus1(a);
printf("a = %d\n",a);//a =Is displayed as 1
return 0;
}
package main
import "fmt"
func plus1(x int) int{
x = x + 1
return x
}
func main(){
a := 1
a1 := plus1(a)
fmt.Println("a =", a) //a =Is displayed as 1
fmt.Println("a + 1 =", a1) //a + 1 =2 is displayed
}
Next, let's pass a pointer.
#include<stdio.h>
int plus1(int *x){
*x = *x + 1 ;
return *x ;
}
int main(void){
int a ;
a = 1 ;
plus1(&a);
printf("a = %d\n",a);//a =2 is displayed
return 0;
}
package main
import "fmt"
func plus1(x *int) int{
*x = *x + 1
return *x
}
func main(){
a := 1
a1 := plus1(&a)
fmt.Println("a =", a) //a =2 is displayed
fmt.Println("a + 1 =", a1) //a + 1 =2 is displayed
}
The result has changed.
If you pass the variable ʻa`` normally, the function will be passed a copy of
ʻa. So the changes are not applied to the original `ʻa
.
When the ~~ pointer is passed, the address where ʻa`` is stored is directly modified, so the process of" adding 1 to a "is changed to the number in the address pointed to by a. It has changed to the process of "adding 1". So in the end, the value of the variable
ʻa`` looking at the same place also goes from 1 to 2. ~~
It's natural for someone who can do it, but I've kept it ambiguous so far, so I took this opportunity to review it. I hope it helps someone even a little.
Recommended Posts