duanchazhou6779 2016-06-30 19:54
浏览 29
已采纳

导入的结构用作匿名字段

So I'm trying to write a few Go files such that there is a public facing package and an internal package.

In the public facing package, there is a struct that is nearly identical (missing one field) to an internal struct.

I thought of using an anonymous field in the internal struct, but it doesn't seem to play nicely.


Example:

public/public.go:

package public

type PublicStruct struct {
    Field1 bool `json:"fetchStats"`
}

data/data.go

package data

import publicData "public"

type InternalStruct struct {
    publicData.PublicStruct
    Field2 bool `json:"includeHidden:`
}

filter/filter.go:

package filter

import "data"

func test() {
    tmp := data.InternalStruct{Field1: true, Field2: false}
}

main.go:

package main

import "filter"
import "data"

func main() {
    var tmp data.InternalStruct
    tmp.Field1 = true
    tmp.Field2 = true
    filter.Test()
}

Expected: no issues

Result: filter/filter.go:6: unknown data.InternalStruct field 'Field1' in struct literal


Why does this not work and what should I do to make it work (I'm currently using the duplicate parameters in both structs approach)?


PS: I don't know how to test this in go playground since it involves multiple files.

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-06-30 19:59
    关注

    The issue is that field1 isn't being exported by the public package as it's name is lower cased. If it were instead Field1 then you could access it inside the internal package like MyInternalStructInstance.Field1

    EDIT - Addresses OP's update;

    The syntax you're using for initilization in your main is just wrong. It should be:

    tmp := InternalStruct{PublicStruct: PublicStruct{Field1: true}, Field2: false}
    

    It has nothing to do with the packages or imported vs exported. It can easily be tested on the playground, a complete example is here; https://play.golang.org/p/tbCqFeNStd

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度