如何使用从另一个包导入的结构体?

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

How to use struct that is imported from another package

问题

好的,以下是翻译好的内容:

嗯,我在Player包中有一个名为Player的结构体。

package Player

type Player struct {
    name         string
    speciality   string
}

而且我在main包中有一个main函数

package main

import "pack/Player"

func main() {
    var player Player.Player
    fmt.Print(player.name)
}

但是在编译后,我得到了以下错误信息:

player.name未定义(无法引用未公开的字段或方法name)

我做错了什么?

英文:

Well, I have my struct Player in package Player

package Player

type Player struct {
	name         string
	speciality   string
}

And I have my main function in package main

package main

import "pack/Player"   
 
func main() {   
   var player Player.Player
   fmt.Print(player.name)
}

But after I compile it I get

> player.name undefined (cannot refer to unexported field or method
> name)

What I am doing wrong?

答案1

得分: 30

你需要将结构体的字段导出,以便通过将它们以大写字母开头来访问:

type Player struct {
    Name         string
    Speciality   string
}
英文:

You need to export the fields of your structure in order for them to be accessible by having them start with upper case characters:

type Player struct {
    Name         string
    Speciality   string
}

huangapple
  • 本文由 发表于 2015年10月11日 05:32:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/33059179.html
匿名

发表评论

匿名网友

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

确定