Discussion
Loading...

Post

  • About
  • Code of conduct
  • Privacy
  • Users
  • Instances
  • About Bonfire
marius
@mariusor@metalhead.club  ·  activity timestamp yesterday

Did any #Go developers need code to get a zero value of a struct but without knowing the layout of the struct itself?

The only thing I could come up with was:

func zero[T any](v T) T {
z := &v
zz := reflect.ValueOf(z).Elem()
zz.Set(reflect.Zero(reflect.TypeOf(v)))
return *z
}

And see here an example of usage: https://go.dev/play/p/Aqzc_nRzOcP

I needed it in order to get zero copies of random structs so I could test that some marshal/unmarshal functionality is a bijection.

Is this a decent way to do it? Are there alternatives?

#golang #dev

Go Playground - The Go Programming Language

  • Copy link
  • Flag this post
  • Block
Log in

bonfire.cafe

A space for Bonfire maintainers and contributors to communicate

bonfire.cafe: About · Code of conduct · Privacy · Users · Instances
Bonfire social · 1.0.0-rc.3.21 no JS en
Automatic federation enabled
  • Explore
  • About
  • Members
  • Code of Conduct
Home
Login