Pointer ใน Go part 1

คิดว่าเรื่อง pointer ในภาษา Go นี่อาจจะมีหลายตอน ทั้งๆที่ตอนนี้ก็ไม่ได้มีอะไรในหัว แต่ก็ขอตั้งชื่อ part 1 เอาไว้ก่อน 😅

พอดีว่าไปเจอโค้ดนึง น่าสนใจที่จะเอามาอธิบาย

func NewPointerString(s string) *string {
p := new(string)
*p = s
return …


This content originally appeared on DEV Community and was authored by DEV Community

คิดว่าเรื่อง pointer ในภาษา Go นี่อาจจะมีหลายตอน ทั้งๆที่ตอนนี้ก็ไม่ได้มีอะไรในหัว แต่ก็ขอตั้งชื่อ part 1 เอาไว้ก่อน 😅

พอดีว่าไปเจอโค้ดนึง น่าสนใจที่จะเอามาอธิบาย

func NewPointerString(s string) *string {
    p := new(string)
    *p = s
    return p
}

โค้ดนี้น่าสนใจตรงที่ ความเข้าใจของเราจะคิดว่า ถ้าไม่ new pointer ตัวใหม่ขึ้นมา แล้วมาเขียนแบบนี้

func NewPointerString(s string) *string {
    return &s
}

มันจะทำให้เราได้ address ของ s ตัวเดิมออกไป ซึ่งจะกลายเป็นว่า ค่าที่ return ออกไปมันจะ refer กลับไปหา s ตัวเดียวกัน

แต่ความเป็นจริง เมื่อ s เข้ามาในฟังก์ชัน NewPointerString แล้ว มันจะเป็นการ copy ค่า string เข้ามาในฟังก์ชันนี้อยู่แล้ว และนั่นทำให้ s ในฟังก์ชันเป็นคนละตัวกันกับ string ที่ใส่เข้ามาอยู่แล้ว

ทำให้เราสามารถเขียนแค่

func NewPointerString(s string) *string {
    return &s
}

ก็ได้เช่นกันก็จะทำให้ pointer ตัวที่ return ออกไป refer ไปที่ string คำเดียวกัน แต่เป็นคนละตัวกันแล้ว ลองพิสูจน์ด้วยการพิมพ์ค่า address มันออกมาดูได้ดังนี้

func main() {
    s := "Hi"
    p := NewPointerString(s)

    fmt.Println(p, &s)
}

func NewPointerString(s string) *string {
    return &s
}

output:

0xc00009e220 0xc00009e210

นี่ก็คือผลลัพธ์ที่ได้ เป็นคนละ address กันแล้วครับ


This content originally appeared on DEV Community and was authored by DEV Community


Print Share Comment Cite Upload Translate Updates
APA

DEV Community | Sciencx (2022-03-04T06:11:17+00:00) Pointer ใน Go part 1. Retrieved from https://www.scien.cx/2022/03/04/pointer-%e0%b9%83%e0%b8%99-go-part-1/

MLA
" » Pointer ใน Go part 1." DEV Community | Sciencx - Friday March 4, 2022, https://www.scien.cx/2022/03/04/pointer-%e0%b9%83%e0%b8%99-go-part-1/
HARVARD
DEV Community | Sciencx Friday March 4, 2022 » Pointer ใน Go part 1., viewed ,<https://www.scien.cx/2022/03/04/pointer-%e0%b9%83%e0%b8%99-go-part-1/>
VANCOUVER
DEV Community | Sciencx - » Pointer ใน Go part 1. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/03/04/pointer-%e0%b9%83%e0%b8%99-go-part-1/
CHICAGO
" » Pointer ใน Go part 1." DEV Community | Sciencx - Accessed . https://www.scien.cx/2022/03/04/pointer-%e0%b9%83%e0%b8%99-go-part-1/
IEEE
" » Pointer ใน Go part 1." DEV Community | Sciencx [Online]. Available: https://www.scien.cx/2022/03/04/pointer-%e0%b9%83%e0%b8%99-go-part-1/. [Accessed: ]
rf:citation
» Pointer ใน Go part 1 | DEV Community | Sciencx | https://www.scien.cx/2022/03/04/pointer-%e0%b9%83%e0%b8%99-go-part-1/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.