Use private struct members in a template

No… you can’t easily read unexported struct members from outside the package they were defined.

What you could do is define another struct with the members public and return that instead, eg playground

package main

import (
	"fmt"
)

type DontMessWithMe struct {
	a int
	b string
}

type DontMessWithMeData struct {
	A int
	B string
}

func (d *DontMessWithMe) Data() *DontMessWithMeData {
	return &DontMessWithMeData{
		A: d.a,
		B: d.b,
	}
}

func main() {
	d := DontMessWithMe{a: 1, b: "potato"}
	data := d.Data()
	fmt.Printf("data = %#v\n", data)
}

You could also define the data in a sub structure and return a copy of that, eg (playground)

package main

import (
	"fmt"
)

type DontMessWithMeData struct {
	A int
	B string
}

type DontMessWithMe struct {
	private DontMessWithMeData
}

func (d *DontMessWithMe) Data() *DontMessWithMeData {
	privateCopy := d.private
	return &privateCopy
}

func main() {
	d := DontMessWithMe{private: DontMessWithMeData{A: 1, B: "potato"}}
	data := d.Data()
	fmt.Printf("data = %#v\n", data)
}

this is probably more efficient but changes the datastructure more.

1 Like