douzhi2760 2016-12-05 08:56
浏览 16
已采纳

默认结构值

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 value so I need to check if it's been set by me or initialised as such. Is there any way to tell the difference between them at all?

Considering the following code... I need to be able to tell the difference between testIntOne and testIntTwo but they look the same!

package main

import "log"

type test struct {
    testIntOne int
    testIntTwo int
}

func main() {
    s := test{testIntOne: 0}

    log.Println(s)
}
  • 写回答

1条回答 默认 最新

  • duanpo7282 2016-12-05 09:00
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)