Copy struct with private field

137 views
Skip to first unread message

Archos

unread,
Nov 9, 2011, 11:18:58 AM11/9/11
to golang-nuts
Any way to copy struct with private fields?

I get a command to run `cmd` and since it could be run several times,
before of call cmd.Wait(), then I would want copy it

// * * *

cmd := exec.Command(name, arg...)

func copy(cmd *exec.Cmd) *exec.Cmd {
cmd_ := *cmd
return &cmd_
}

// * * *

but I get an error:

implicit assignment of unexported field 'err' of exec.Cmd in assignment

Jeremy Wall

unread,
Nov 9, 2011, 11:23:23 AM11/9/11
to Archos, golang-nuts
Wouldn't dereferencing the pointer and assigning to a variable
effectively copy it? I *think* it would but I'm actually not sure so
I'm asking the wider list.

Jan Mercl

unread,
Nov 9, 2011, 11:46:15 AM11/9/11
to golan...@googlegroups.com
On Wednesday, November 9, 2011 5:18:58 PM UTC+1, Archos wrote:
Any way to copy struct with private fields?

No. Intentionally not allowed. There may be some state in it which must be initialized and/or not reused and/or unique to its instance etc. Knowing/looking at the (imported package) sources doesn't help as the struct type private internals (and their semantics) can change at any time in the future - without breaking the public/exported API.


"If T is a struct type with non-exported fields, the assignment must be in the same package in which T is declared, or x must be the receiver of a method call. In other words, a struct value can be assigned to a struct variable only if every field of the struct may be legally assigned individually by the program, or if the assignment is initializing the receiver of a method of the struct type."
Reply all
Reply to author
Forward
0 new messages