英文:
returning slice of structs from another package - prints data but not fields
问题
假设我有两个包,"main"和"src/test"。
在test包中,我有一个结构体和一个函数,用于分配数据并返回它。
package abc
type Tp struct {
uid int
test string
}
func Testing() []Tp {
var data []Tp
temp := Tp{1, "b"}
data = append(data, temp)
temp = Tp{2, "c"}
data = append(data, temp)
return data
}
在main包中,我想获取Tp类型的结构体切片并访问字段,像这样:
package main
import (
"fmt"
"testing/src/abc"
)
func main() {
t := abc.Testing()
fmt.Println(t[0].test) // <--- 错误:未定义(类型excel.Tp没有字段或方法)
}
上面我得到了错误 - 类型excel.Tp没有字段或方法
但是如果我使用fmt.Println(t)
或fmt.Println(t[0])
打印数据,它可以正常输出。
之后,我需要循环遍历切片并访问底层结构体的字段。
如何返回带有字段的结构体?
数据确实返回,并且是abc.Tp类型的。我尝试了很多方法,比如使用整个切片的指针和将结构体移动到周围,但是到目前为止都没有成功。作为一个初学者,我一定是犯了一个导致这个结果的基本错误。
英文:
Let's say I have a two packages, "main" and "src/test"
At the test package I have the struct and function that assigns data end returns it
package abc
type Tp struct {
uid int
test string
}
func Testing() []Tp {
var data []Tp
temp := Tp{1, "b"}
data = append(data, temp)
temp = Tp{2, "c"}
data = append(data, temp)
return data
}
in the main package I want to get the slice of structs type Tp and access the fields, like so:
package main
import (
"fmt"
"testing/src/abc"
)
func main() {
t := abc.Testing()
fmt.Println(t[0].test) // <--- error undefined (type excel.Tp has no field or method
}
above i get error - type excel.Tp has no field or method
but if i print data with fmt.Println(t)
or fmt.Println(t[0])
it prints data without a problem
Later I will need to loop over the slice and access underlying stuct's fields
How can I return struct with fields?
The data ARE returning and are of type abc.Tp I tried a lot of things, like pointers to the whole slice and movie struct around, but nothing worked so far. As a beginner I must be doing a fundamental mistake that results in this result
答案1
得分: 1
以小写字母开头的标识符被视为未导出的。未导出的标识符无法从其声明所在的包之外访问。换句话说,使用以大写字母开头的标识符来使它们被导出,以便其他包可以访问它们。更多信息请参见:https://go.dev/ref/spec#Exported_identifiers
type Tp struct {
Uid int
Test string
}
英文:
Identifiers starting with lowercase are considered unexported. Unexported identifiers are not accessible from outside of the package in which they were declared. In other words, use idnetifiers starting with Uppercase to make them exported so that other packages can access them. For more info, see: https://go.dev/ref/spec#Exported_identifiers
type Tp struct {
Uid int
Test string
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论