• Home
  • About
    • Jiwon Jeong photo

      Jiwon Jeong

      끊임없이 배우며 성장하는 엔지니어

    • Learn More
    • Email
    • Github
  • Posts
    • All Posts
    • All Tags
    • All Categories
  • Projects

Go Lang 특성2

13 Dec 2021

Reading time ~1 minute

Call by Value 심화

  • 구조체 Call by Value
import (
	"fmt"
)

type Person struct {
	name string
	age  int
}

func (p Person) toString() {
	p.age++
	print(&p, "\n")
}

func main() {
	p1 := Person{name: "gildong", age: 27}
	p2 := Person{name: "younghee", age: 25}

	print("할당된 두 변수의 주소값 \n")
	print("p1의 주소 : ", &p1, "\n", "p2의 주소 : ", &p2, "\n")

	p1.toString()
	p2.toString()

	fmt.Println(p1.age)
	fmt.Println(p2.age)
}

/* 

----------- 결과 ----------

할당된 두 변수의 주소값 
p1의 주소 : 0xc0000cdf28
p2의 주소 : 0xc0000cdf10
0xc0000cdeb8
0xc0000cdeb8
27
25

*/

  • toString 함수 내에서 print한 것(p1의 주소 : 0xc0000cdf28)과 함수 밖에서 호출했을 때의 결과(0xc0000cdeb8)가 다르다.
    • toString 함수는 call by value 형태로 호출하기 때문에 복사본을 전달하였다.
    • 따라서, golang에서는 구조체에서 포인터를 사용하여 call by reference 형태로 작성하면 값을 반영하여 변경할 수 있다.
import (
	"fmt"
)

type Person struct {
	name string
	age  int
}

func (p *Person) toString() {
	p.age++
	print(&p, "\n")
}

func main() {
	p1 := Person{name: "gildong", age: 27}
	p2 := Person{name: "younghee", age: 25}

	print("할당된 두 변수의 주소값 \n")
	print("p1의 주소 : ", &p1, "\n", "p2의 주소 : ", &p2, "\n")

	p1.toString()
	p2.toString()

	fmt.Println(p1.age)
	fmt.Println(p2.age)
}

/* 

----------- 결과 ----------

할당된 두 변수의 주소값 
p1의 주소 : 0xc0000cdf28
p2의 주소 : 0xc0000cdf10
0xc0000cdeb8
0xc0000cdeb8
28
26


*/



개발일기 Share Tweet +1