1

Is this valid syntax for initializing a struct in Go?

id := struct { name, ltype, value }

The fields are all strings. The actual error message I get is "syntax error: unexpected }". Maybe you cant initialize anonymous structs this way ?

2 Answers 2

7

No type inference for you!

name := "a"
ltype := "b"
value := "c"
id := struct { name, ltype, value string } { name, ltype, value }
Sign up to request clarification or add additional context in comments.

4 Comments

Context: Seinfeld. :)
And there was I thinking I could save some typing - may as well go back to using new() and init all fields by hand!
You don't need to name the fields in the data part, and you only need one string definition which can make it shorter if you want id := struct {name, ltype, value string}{name, ltype, value}
Its a shame - that struct is embedded inside another struct in my code, so initializing this way is tedious. Are the inference rules documented anywhere?
0

You can also initialize the value inline.

id := struct{ name, ltype, value string }{"a", "b", "c"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.