在Golang中,是否可以给nil起一个别名?

huangapple go评论77阅读模式
英文:

Is it possible to alias nil in Golang

问题

在整理我的项目时,我注意到许多地方都有nil比较。我希望将nil替换为NULLNull。我尊重Golang规范,但我想知道我们是否可以这样做。

我已经对interface{}context.Context进行了如下替换:

type CON = context.Context 
type Any = interface{}
英文:

While organizing my projects, I observe nil comparisons in many places. I wish to replace nil with NULL or Null. I respect Golang specs, but I am curious if we can do this.

I already did it for interface{} , context.Context as follows.

type CON = context.Context 
type Any = interface{}

答案1

得分: 4

你不能这样做。你展示的是类型别名。nil不是一种类型,它是一种具有不同类型的值。你可能希望创建一个具有nil值的常量,类似于创建一个值为0的常量,但是编译器明确禁止这样做:

const NULL = nil

错误:const初始化器不能为nil

根据语言规范
> 有布尔常量、符文常量、整数常量、浮点数常量、复数常量和字符串常量。

这些类型都不能具有nil值,因此无法创建一个nil常量。

你也可以尝试创建一个保存nil值的变量,但是如果你不声明变量的类型,你会发现这样做是行不通的:

var NULL = nil

错误:使用了未类型化的nil

你可以通过为变量添加一个可为nil的类型来使其合法,但是这样做将不再非常有用,因为它只能与该特定类型进行比较。

英文:

You cannot. What you show there are type aliases. nil is not a type. It is a value of a wide range of different types. You may hope that you can make a constant with a value of nil, similar to how you can make a constant of value 0, but this is explicitly disallowed by the compiler:

const NULL = nil

Error: const initializer cannot be nil

According to the language specification:
> There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants.

None of these types can have a nil value, therefore a nil constant is not possible.

You might also try to make a variable which holds the value nil, but you'll find the problem that it doesn't work if you don't declare the type of the variable:

var NULL = nil

Error: use of untyped nil

You can make it legal by adding a nilable type to the variable, but then it will no longer be very useful as it will only be comparable to that specific type.

huangapple
  • 本文由 发表于 2021年6月13日 14:24:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/67955493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定