DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on

4 2

ใช้ reflect package ช่วยเพื่อ Set Zero value ของ type ใดๆ ของ Go

#go

มีคำถามในกลุ่ม facebook Golang Thailand ว่า

Alt Text

ซึ่งสำหรับข้อแรกนั้นเราใช้ reflect package ช่วยได้

ซึ่งโค้ดที่ได้เป็นแบบนี้

package main

import (
    "fmt"
    "reflect"
)

func SetToNil(a interface{}) {
    v := reflect.ValueOf(a).Elem()
    v.Set(reflect.Zero(v.Type()))
}

func main() {
    n := 10
    a := &n
    fmt.Println(a)
    SetToNil(&a)
    fmt.Println(a)

    s := "Hello"
    ss := &s
    fmt.Println(ss)
    SetToNil(&ss)
    fmt.Println(ss)
}
Enter fullscreen mode Exit fullscreen mode

เราประกาศ parameter เป็น interface{} ซึ่งแน่นอนว่าจะส่งค่าอะไรมาก็ได้ แต่อย่างไรก็ตาม ถ้าเรายังต้องการแก้ไขค่าของตัวแปรที่ส่งมา ยังไงตอนเรียกใช้ก็ต้องส่ง address ของตัวแปรที่ส่งมา คือ pointer นั่นเองเช่นผมเรียก SetToNil(&a) ถึงทำงานได้ ถ้าส่งแค่ SetToNil(a) จะทำให้แก้ไขค่าของตัวแปร a ไม่ได้แน่นอนเพราะไม่รู้ address

ส่วนกลไกของ reflect ที่ใช้คือเราใช้ reflect.ValueOf function ในการแปลงค่าเป็น reflect.Value แล้วจึงเรียก method Elem() เพราะ a เป็น addressable (pointer) value ทำให้ Elem คือการอ้างถึง address ที่โดนชี้อยู่ด้วย pointer a (เหมือนเราใช้ operator *a แบบนี้)

จากนั้นจึงใช้ method Set เพื่อเซตค่าใหม่ ส่วน Zero value เราได้มาโดยใช้ฟังก์ชัน reflect.Zero แล้วจึงส่งค่า type ให้โดยใช้ type ของ v โดยใช้ method v.Type() นั่นเอง

ขอฝาก Buy Me a Coffee

สำหรับท่านใดที่อ่านแล้วชอบโพสต์ต่างๆของผมที่นี่ ต้องการสนับสนุนค่ากาแฟเล็กๆน้อยๆ สามารถสนับสนุนผมได้ผ่านทาง Buy Me a Coffee คลิ๊กที่รูปด้านล่างนี้ได้เลยครับ

Buy Me A Coffee

ส่วนท่านใดไม่สะดวกใช้บัตรเครดิต หรือ Paypal สามารถสนับสนุนผมได้ผ่านทาง PromptPay โดยดู QR Code ได้จากโพสต์ที่พินเอาไว้ได้ที่ Page DevDose ครับ https://web.facebook.com/devdoseth

ขอบคุณครับ 🙏

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay