How can I define a `const *DataType`

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

How can I define a `const *DataType`

问题

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

// 空列表的表示
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.

// Representation of the empty list
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语言中,可以使用函数。例如,

package main

import "fmt"

type List struct{}

func IsEmptyList(list *List) bool {
    // 表示空列表
    return list == (*List)(nil)
}

func main() {
    fmt.Println(IsEmptyList((*List)(nil)))
}

输出结果:

true

该函数将被内联。

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

In Go, use a function. For example,

package main

import "fmt"

type List struct{}

func IsEmptyList(list *List) bool {
	// Representation of the empty list
	return list == (*List)(nil)
}

func main() {
	fmt.Println(IsEmptyList((*List)(nil)))
}

Output:

true

The function will be inlined.

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

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:

确定