kok202
[2019.03.08] Go lang (Struct)

2019. 3. 8. 11:28[공부] 영상/GoLanguage

Class가 없음 type struct 로 대체

- 키워드를 줄이기 위해서 용어를 하나로 통일한 듯

- 생성자도 자동으로 지원

- 메소드는 네임스페이스 방식처럼 알려줘서 지원함


package main

import "fmt"

type car struct {
    runTime uint16
    runSpeed uint16
}

func (carTemp car) calcRunningDistance() float64 {
    return float64(carTemp.runTime * carTemp.runSpeed)
}

func main() {
    carA := car{runTime: 100, runSpeed: 60}
    carB := car{runTime: 200}
    carC := car{100, 80}
    fmt.Println(carA.runTime)
    fmt.Println(carA.runSpeed)
    fmt.Println(carA.calcRunningDistance())
    fmt.Println(carB.runTime)
    fmt.Println(carB.runSpeed)
    fmt.Println(carB.calcRunningDistance())
    fmt.Println(carC.runTime)
    fmt.Println(carC.runSpeed)
    fmt.Println(carC.calcRunningDistance())
}






메소드 호출 방식이 Call by value 다.

매개변수 접근을 -> 로 안해서 좋다.


package main

import "fmt"

type car struct {
    runTime uint16
    runSpeed uint16
}

func (carTemp car) show() {
    fmt.Printf("%d %d\n", carTemp.runTime, carTemp.runSpeed)
}

func (carTemp car) swipeTimeAndSpeedByValue() {
    temp := carTemp.runTime
    carTemp.runTime = carTemp.runSpeed
    carTemp.runSpeed = temp
}

func (carTemp *car) swipeTimeAndSpeedByPointer() {
    temp := carTemp.runTime
    carTemp.runTime = carTemp.runSpeed
    carTemp.runSpeed = temp
}

func (carTemp *car) showPointerInMethod() {
    fmt.Println(carTemp)
    fmt.Println(*carTemp)
}

func main() {
    carA := car{runTime: 100, runSpeed: 60}
    carA.show()
    carA.swipeTimeAndSpeedByValue()
    carA.show()
    carA.swipeTimeAndSpeedByPointer()
    carA.show()
    carA.showPointerInMethod()
}


result

100 60
100 60
60 100
&{60 100}
{60 100}