Default struct values

前端 未结 1 1363
你的背包
你的背包 2020-12-07 00:24

In Go I get that there are default values for types. Take int in this case which is initialised as a 0.

I have an issue where for me a 0 in an int can be a valid va

相关标签:
1条回答
  • 2020-12-07 00:30

    You can't tell the difference, it is not tracked whether a field (or a variable) has been set or not.

    Using a pointer

    You may use a pointer which has a nil zero value, so if not set, you can tell:

    type test struct {
        testIntOne *int
        testIntTwo *int
    }
    
    func main() {
        s := test{testIntOne: new(int)}
    
        fmt.Println("testIntOne set:", s.testIntOne != nil)
        fmt.Println("testIntTwo set:", s.testIntTwo != nil)
    }
    

    Output (try it on the Go Playground):

    testIntOne set: true
    testIntTwo set: false
    

    Of course new() can only be used to obtain a pointer to an int value being 0. See this question for more options: How do I do a literal *int64 in Go?

    Using a method

    You may also use a method to set a field, which could take care of additionally tracking the "isSet" property. In this case you must always use the provided method to set the field. Best is to make fields unexported, so others (outside your package) won't have direct access to them.

    type test struct {
        testIntOne int
        testIntTwo int
    
        oneSet, twoSet bool
    }
    
    func (t *test) SetOne(i int) {
        t.testIntOne, t.oneSet = i, true
    }
    
    func (t *test) SetTwo(i int) {
        t.testIntTwo, t.twoSet = i, true
    }
    
    func main() {
        s := test{}
        s.SetOne(0)
    
        fmt.Println("testIntOne set:", s.oneSet)
        fmt.Println("testIntTwo set:", s.twoSet)
    }
    

    Output (try it on the Go Playground):

    testIntOne set: true
    testIntTwo set: false
    
    0 讨论(0)
提交回复
热议问题