dtwbp26022 2019-08-06 19:40
浏览 62

为什么在遍历结构片段时无法访问结构字段

I have a function in a package which returns a slice of a specific struct I defined in my package, then I'm importing this package to another main package and I want to iterate over the slice returned from the function and access the structs fields, I'm getting "undefined" error.

"s.a undefined (cannot refer to unexported field or method a)"

What am I missing?

thanks for the help.

the packages code:

package test_package

import "fmt"

type Struct struct {
    a string
    b string
}

func ReturnStructSlice() ([]Struct){
    s1 := Struct{"a", "b"}
    s2 := Struct{"c", "d"}

    structSliceToReturn := []Struct{s1, s2}

    for _, s := range structSliceToReturn {
        fmt.Println(" ", s.a)
    }

    return structSliceToReturn
}

this is the main package:

package main

import (
    t "/test_package"
    "fmt"
)


func main() {
    sList := t.ReturnStructSlice()
    for _, s := range sList {
        fmt.Println(" ", s.a) \\ here I'm getting the error
    }
}
  • 写回答

1条回答 默认 最新

  • dongsaohu6429 2019-08-06 19:48
    关注

    You need to capitalize the first letter of struct members to export them.

    type Struct struct {
        A string
        B string
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私