Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
761 views
in Technique[技术] by (71.8m points)

go - Check for nil in pointer receiver function

Is it possible that in go pointer receiver function the pointer will be nil? In which case?

Sample code:

type JSONBytes []byte

func (buffer *JSONBytes) Deserialize() *map[uint64]string {
    if buffer == nil {     
        fmt.Println("buffer is <nil>")  
        return nil
    }
    if *buffer == nil {     
        fmt.Println("*buffer is <nil>") 
        return nil
    }
    
    var f interface{}
    err := json.Unmarshal(*buffer, &f)
    if err != nil {
        fmt.Println(err)
        return nil
    }
    data := f.(map[string]interface{})

    m := make(map[uint64]string)
    for k, v := range data {
        vm := v.(map[string]interface{})
        pid, err := strconv.ParseUint(k, 10, 32)
        if err == nil {
            m[pid] = vm["value"].(string)
        }
    }
    return &m
}

While debugging I realized that even for:

var buff JSONBytes = nil
buff.Deserialize()

value of buffer is not nil, only condition *buffer == nil is true.

Is it safe to check only: if *buffer == nil.

Is it possible that buffer will be nil? When?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...