상세 컨텐츠

본문 제목

Go 언어에서의 포인터

Go lang

by techbard 2022. 3. 17. 07:57

본문

반응형
package main

import (
	"fmt"
)

func main() {
	a := [3]int{1, 2, 3}
	b := &a[0]
	c := &a[1]

	fmt.Printf("%v %p %p\n", a, b, c)
}

// 결과
//
// [1 2 3] 0xc0000ae078 0xc0000ae080

// Test84
package main

import (
	"fmt"
)

func main() {
	var ms *myStruct
	fmt.Println(ms)
	ms = new(myStruct)
	fmt.Println(ms)

	fmt.Println("==========")

	(*ms).value = 10
	fmt.Println((*ms).value)

	// syntatic sugar
	fmt.Println("==========")
	ms.value = 20
	fmt.Println(ms.value)
}

type myStruct struct {
	value int
}


// 결과
//
// <nil>
// &{0}
// ==========
// 10
// ==========
// 20

// Test85
package main

import (
	"fmt"
)

func main() {
	a := map[string]string{"foo": "bar", "baz": "buz"}
	b := a
	fmt.Println(a, b)
	a["foo"] = "qoo"
	fmt.Println(a, b)
}

// 결과
//
// map[baz:buz foo:bar] map[baz:buz foo:bar]
// map[baz:buz foo:qoo] map[baz:buz foo:qoo]

  • Type with pointers
  • All assignment operations in Go are copy operation
  • Slices and maps contain internal pointers, so copies point to same underlying data

package main

import (
	"fmt"
)

func updateName(s string) {
	s = "wedge"
}

func updateMenu(m map[string]float64) {
	m["coffee"] = 2.99
}

func main() {
	// group A types -> strings, ints, bools, floats, arrays, structs
	name := "tifa"
	updateName(name)
	fmt.Println(name)

	// group B types -> slices, maps, functions
	menu := map[string]float64{
		"pie":       5.95,
		"ice cream": 3.99,
	}

	updateMenu(menu)
	fmt.Println(menu)

}

// 결과
//
// tifa
// map[coffee:2.99 ice cream:3.99 pie:5.95]
반응형

관련글 더보기

댓글 영역