英文:
Is it possible to alias nil in Golang
问题
在整理我的项目时,我注意到许多地方都有nil
比较。我希望将nil
替换为NULL
或Null
。我尊重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 nil
able type to the variable, but then it will no longer be very useful as it will only be comparable to that specific type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论