英文:
import struct in go, get "not a type" error
问题
我导入了另一个包中定义的结构体,在尝试使用它来构造一个字面量时,出现了“不是类型”的错误。
在publish.go中:
type Book struct {
Name string
Author string
Published bool
}
在store.go中:
import "publish"
func Init() {
var reading publish.Book
b := &reading{
Name: "Learn Go Lang",
Author: "Rob",
Published: true,
}
}
错误信息:reading不是一个类型。
英文:
I import a struct defined in another package, when try to use it to construct a literal, get a "not a type" error.
In publish.go
type Book struct {
Name string
Author string
Published bool
}
In store.go
import "publish"
func Init() {
var reading publish.Book
b := &reading {
Name: "Learn Go Lang",
Author: "Rob",
Published: true
}
}
Error: reading is not a type
答案1
得分: 4
这里你试图创建一个类型为"reading"的结构体:
b := &reading{
Name: "Learn Go Lang",
Author: "Rob",
Published: true
}
你想要的是一个类型为publish.Book的结构体:
b := &publish.Book{
Name: "Learn Go Lang",
Author: "Rob",
Published: true,
}
另外,在多行结构体声明的最后一个字段后面也需要加上逗号。
英文:
Here you try to make a struct of Type "reading"
b := &reading {
Name: "Learn Go Lang",
Author: "Rob",
Published: true
}
What you want is a struct of type publish.Book
b := & publish.Book {
Name: "Learn Go Lang",
Author: "Rob",
Published: true,
}
plus you also need a comma at the end of the last in a multi-line struct declaration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论