pointers - How exactly are interface variables implemented in Go? -
in below code snippet, i'd understand gets stored in iperson
when contents still uninitialized: value of 0-bytes? or pointer under hood (and initialized 0-bytes of course)? in case, happens @ iperson = person
?
if iperson = person
makes copy of person
, happens when object implementing iperson
different size/memory footprint gets assigned iperson
? understand iperson
variable stored on stack, size must fixed. mean heap used under hood, iperson
implemented pointer, assignments still copy object, demonstrated above code? here's code:
type person struct{ name string } type iperson interface{} func main() { var person person = person{"john"} var iperson iperson fmt.println(person) // => john fmt.println(iperson) // => <nil> ...so looks pointer iperson = person // ...this seems making copy fmt.println(iperson) // => john person.name = "mike" fmt.println(person) // => mike fmt.println(iperson) // => john ...so looks wasn't pointer, // or @ least copied }
(this question result of me having second thoughts on precise factual correctness of answer why runtime error on io.writerstring?. decided try investigation understand how interface variables , assignments them work in go.)
edit: after having received few useful answers, i'm still puzzled this:
iperson = person iperson = &person
—both legal. however, me, raises question of why compiler allows such weak typing occur? 1 implication of above this:
iperson = &person var person2 = iperson.(person) # panic: interface conversion: interface *main.person, not main.person
whereas changing first line fixes it:
iperson = person var person2 = iperson.(person) # ok
...so it's not possible determine statically whether iperson
holds pointer or value; , seems can assign either 1 @ runtime no errors raised. why such design decision made? purpose serve? not fit within "type safety" mindset.
when execute following line:
iperson = person
you storing person
value in interface variable. since assignment struct performs copy, yes code taking copy. retrieve struct inside interface you'll need take copy:
p := iperson.(person)
so you'd want mutable types. if instead want store pointer struct in interface variable, need explicitly:
iperson = &person
as far goes on under hood, right interface variables allocate heap space store values larger pointer, not visible user.
Comments
Post a Comment