douzhi2988 2018-05-24 13:39
浏览 12
已采纳

如何检查是否已设置int变量?

Lets say I have a variable num.

Before I can evaluate an if statement, I need to check if this variable has been set in the first place. Typically I would use either -1, 0 or math.MaxInt32/math.MinInt32 but for this task I need to check if my program has set its value.

I tried nums := nil and in my if statement I had something like if nums == nil || ....

But when creating the nums variable I was surprised to get the error cannot convert nil to type int. How I can achieve what I want to do?

To make it clear: This is a leetcode question and don't have control of the inputs, they put all sorts of numbers inside include math.MaxInt32, math.MinInt32

Full code:

func thirdMax(nums []int) int {

    dict := make(map[int]int, 0)

    varmaxOne := math.MinInt32
    maxTwo := math.MinInt32
    maxThree := math.MinInt32


    for _, value := range nums {

        if value >= maxOne && dict[value] < 1 {

            maxThree = maxTwo
            maxTwo = maxOne
            maxOne = value

        }else if value >= maxTwo && dict[value] < 1{
            maxThree = maxTwo
            maxTwo = value
        } else if value >= maxThree && dict[value] < 1 {
            maxThree = value
        }

        dict[value] += 1
    }

    if maxThree == math.MinInt32 {
        return maxTwo
    }
    return maxThree

}

func max(a int, b int) int {
    if a > b {
        return a
    }
    return b
}

Test

func TestThirdMax(t *testing.T) {
    //array := []int{2, 3, -1, -9, 11, 4, 3, 0, -100}
    //array := []int{2, 2, 3, 1}
    array := []int{1,2,-2147483648}
    //array := []int{3,2,1}
    result := thirdMax(array)

    if result != 2 {
        t.Errorf("Expected 2, but it was %d instead.", array)
    }
}

The code above use math.MinInt32, but fails with the input given. The idea was to have nil instead and put a check in the if statement, but fails as stated above.

  • 写回答

2条回答 默认 最新

  • dongse5408 2018-05-24 13:55
    关注

    As the comments suggest, the Zero Value for all int types in Go is 0. If 0 is a possible value for a number, and you need to check if it has been assigned or not, then you will probably want to use a Struct type with some metadata attached, rather than the primitive type.

    As usual for these sorts of questions, there are precedents for this in the standard library.

    Take a look at the database/sql package's Null types. These types are also justified by implementing Scanner, but you can use the same idea any time you need to check whether a primitive value should truly be equal to Null, rather than it's zero value.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?