英文:
Initialize custom int type in Go
问题
在Go语言中,创建一个类型是有效的:
type Num int
但是如何初始化这个类型呢?使用make(Num, 2)似乎不起作用。
英文:
In Go it is valid to create a type:
type Num int
but how can one then initialize that type? make(Num, 2) does not seem to work.
答案1
得分: 44
将类型初始化为您将初始化的基础类型。在您的示例中,基础类型是int
。例如,
package main
import (
"fmt"
)
type Num int
func main() {
var m Num = 7
n := Num(42)
fmt.Println(m, n)
}
输出:7 42
内置函数make接受类型T,该类型必须是切片、映射或通道类型。
英文:
Initialize the type as you would initialize the underlying type. In your example, the underlying type is an int
. For example,
package main
import (
"fmt"
)
type Num int
func main() {
var m Num = 7
n := Num(42)
fmt.Println(m, n)
}
Output: 7 42
The built-in function make takes a type T, which must be a slice, map or channel type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论