mixture of field:value and value initializers

Go

Go Problem Overview


Why can I not create the following, with an anonymous field?

type T1 struct {
	T1_Text string
}

type T2 struct {
	T2_Text string
	T1
}

used in func ..

t := T2{
	T2_Text: "Test",
	T1{T1_Text: "Test"},
}

Gives me: mixture of field:value and value initializers?

Go Solutions


Solution 1 - Go

A brief explanation.

The reason you get that is because you are allowed to only use one of the two types of initializers and not both.

i.e. you can either use field:value or value.

Using your example you either do

field:value

t := T2{
    T2_Text: "Test",
    T1: T1{T1_Text: "Test"},
}

or only values

t := T2{
    "Test",
    T1{"Test"},
}

Hope that explains the why

Solution 2 - Go

Missing the attribute name T1 for assignment.

t := T2{
	T2_Text: "Test",
	T1:      T1{T1_Text: "Test"},
}

P.S. Just moved @twotwotwo's comment to an answer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris G.View Question on Stackoverflow
Solution 1 - GoDee SView Answer on Stackoverflow
Solution 2 - GowuliwongView Answer on Stackoverflow