How can I define a `const *DataType`

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

How can I define a `const *DataType`

问题

我正在使用Go语言编写一个Lisp变种,并且想要为NilEmptyList定义常量。这些常量将在整个代码库中被引用,但我希望防止它们被意外重新定义。

  1. // 空列表的表示
  2. var EmptyList = (*List)(nil)

在这里我不能使用const的原因有两个:

  1. const定义不能是nil
  2. const定义不能是指针

我有哪些选项可以确保EmptyList始终是nil指针?

英文:

I'm writing a Lisp variant in Go and want to define constants for Nil and EmptyList. These will be referenced throughout the codebase, but I want to prevent them from being accidentally re-defined.

  1. // Representation of the empty list
  2. var EmptyList = (*List)(nil)

I can't use a const here for two reasons:

  1. const definitions cannot be nil
  2. const definitions cannot be pointers

What options do I have to ensure EmptyList is always the nil pointer?

答案1

得分: 1

在Go语言中,可以使用函数。例如,

  1. package main
  2. import "fmt"
  3. type List struct{}
  4. func IsEmptyList(list *List) bool {
  5. // 表示空列表
  6. return list == (*List)(nil)
  7. }
  8. func main() {
  9. fmt.Println(IsEmptyList((*List)(nil)))
  10. }

输出结果:

  1. true

该函数将被内联。

  1. $ go tool compile -m emptylist.go
  2. emptylist.go:7: can inline IsEmptyList
  3. emptylist.go:13: inlining call to IsEmptyList
  4. emptylist.go:7: IsEmptyList list does not escape
  5. emptylist.go:13: IsEmptyList((*List)(nil)) escapes to heap
  6. emptylist.go:13: main ... argument does not escape
  7. $
英文:

In Go, use a function. For example,

  1. package main
  2. import "fmt"
  3. type List struct{}
  4. func IsEmptyList(list *List) bool {
  5. // Representation of the empty list
  6. return list == (*List)(nil)
  7. }
  8. func main() {
  9. fmt.Println(IsEmptyList((*List)(nil)))
  10. }

Output:

  1. true

The function will be inlined.

  1. $ go tool compile -m emptylist.go
  2. emptylist.go:7: can inline IsEmptyList
  3. emptylist.go:13: inlining call to IsEmptyList
  4. emptylist.go:7: IsEmptyList list does not escape
  5. emptylist.go:13: IsEmptyList((*List)(nil)) escapes to heap
  6. emptylist.go:13: main ... argument does not escape
  7. $

huangapple
  • 本文由 发表于 2015年10月29日 10:23:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/33404906.html
匿名

发表评论

匿名网友

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

确定