导入的结构用作匿名字段

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.

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