This question already has answers here:
"missing type in composite literal" when passing value to struct
(1 answer)
Missing type in composite literal
(3 answers)
Golang error - missing type in composite literal [duplicate]
(1 answer)
Closed 7 months ago.
I have the following anonymous struct:
func wrapHal(selfHref string) interface{} {
return struct {
_links struct {
self struct {
href string
}
}
}{
_links: {self: {href: selfHref}}, # this line
}
}
However, in "this line, " I get the error missing type in composite literal
How to fix it? It is possible to initiate a anonymous nested struct in Go?
To initialize an anonymous struct, you have to declare the type. You declared the root anonymous struct, but you need to do again for each nested anonymous struct:
func wrapHal(selfHref string) interface{} {
return struct {
_links struct {
self struct {
href string
}
}
}{
_links: struct {
self struct {
href string
}
}{
self: struct {
href string
}{
href: "",
},
},
}
}
This question already has answers here:
Can I construct a slice of a generic type with different type parameters?
(2 answers)
Go generic container with different runtime types
(1 answer)
Closed 8 months ago.
how can I create a map of type map[string]Func[T] where T is a generic type? Here's the code that I have:
type First struct {
FieldA string
}
type Second struct {
FieldB string
}
type MyStructs interface {
First | Second
}
func FirstMapper(data First) error {
fmt.Println(data.FieldA)
return nil
}
type Mapper[T MyStructs] func(data T) error
func main() {
mymap := map[string]Mapper[MyStructs] {
"first": FirstMapper,
}
}
However, I get the following error: cannot use FirstMapper (value of type func(data First) error) as type Mapper[MyStructs] in map literal
Seems that the function FirstMapper for some reason doesn't follow the signature of Mapper[T] type
Any help is really appreciated.
This question already has answers here:
How to initialize a nested struct?
(10 answers)
Initialize nested struct definition
(3 answers)
Closed last year.
I have generated go struct from json.
And it gave me next output:
type PartnerBody87 struct {
Imp []struct {
Bidfloor float64 `json:"bidfloor"`
Secure int `json:"secure"`
Ext struct {
Type string `json:"type"`
Webpush int `json:"webpush"`
} `json:"ext"`
ID string `json:"id"`
Tagid string `json:"tagid"`
} `json:"imp"`
}
I tried different ways, and cannot find proper one of how to initiate the value for
Imp []struct.
Update:
I know that I can split struct into few types. But I'm curious if Go have ability to set everything in 1 struct - than how to use it?
You can split them like this:
type PartnerBody87 struct {
Imp []Imp `json:"imp"`
}
type Imp struct {
Bidfloor float64 `json:"bidfloor"`
Secure int `json:"secure"`
Ext Ext `json:"ext"`
ID string `json:"id"`
Tagid string `json:"tagid"`
}
type Ext struct {
Type string `json:"type"`
Webpush int `json:"webpush"`
}
This question already has an answer here:
"used as value" in function call
(1 answer)
Closed 4 years ago.
I am trying one simple Go struct with value and pointer receiver functions. I am not able to pass one string as an argument to pointer receiver function to modify the struct data. Can anyone please help on this?
Code:
package main
import (
"fmt"
)
type book struct {
author string
name string
category string
price int16
}
func (b book) greet() string {
return "Welcome " + b.author
}
func (b *book) changeAuthor(author string) {
b.author = author
}
func main() {
book := book{author: "Arockia",
name: "Python shortcuts",
category: "IT",
price: 1500}
fmt.Println(book.author)
fmt.Println(book.greet())
fmt.Println(book.changeAuthor("arulnathan"))
fmt.Println(book.author)
}
Error:
.\struct_sample.go:29:31: book.changeAuthor(string("arulnathan")) used as value
func (b *book) changeAuthor(author string) {
b.author = author
}
changeAuthor does not have a return type. You cannot use Println or any other function/method which expects a parameter in your case.
To solve this, first you can change your author as book.changeAuthor("arulnathan") and the print book.author.
You can not print changeAuthor while it return nothing.
book.changeAuthor("arulnathan")
fmt.Println(book.author)
I have two struct having the same members, I want to copy one struct to another, see the pseudo code below:
type Common struct {
Gender int
From string
To string
}
type Foo struct {
Id string
Name string
Extra Common
}
type Bar struct {
Id string
Name string
Extra Common
}
Then I have foo of struct Foo, and bar of struct Bar, Is there any way to copy bar from foo?
Use a conversion to change the type. The following code uses a conversion to copy a value of type Foo to a value of type Bar:
foo := Foo{Id: "123", Name: "Joe"}
bar := Bar(foo)
playground example
The conversion only works when the underlying types are identical except for struct tags.
https://github.com/jinzhu/copier (same author of gorm) is also quite a good one, I have nested structs and all I do is:
copier.Copy(&employees, &user)
works great
If you would like to copy or clone to a different struct, I would suggest using deepcopier
It provides nice features like skipping, custom mapping, and forcing. below is an example from github:
Install:
go get -u github.com/ulule/deepcopier
Example:
package main
import (
"fmt"
"github.com/ulule/deepcopier"
)
// Model
type User struct {
// Basic string field
Name string
// Deepcopier supports https://golang.org/pkg/database/sql/driver/#Valuer
Email sql.NullString
}
func (u *User) MethodThatTakesContext(ctx map[string]interface{}) string {
// do whatever you want
return "hello from this method"
}
// Resource
type UserResource struct {
//copy from field "Name"
DisplayName string `deepcopier:"field:Name"`
//this will be skipped in copy
SkipMe string `deepcopier:"skip"`
//this should call method named MethodThatTakesContext
MethodThatTakesContext string `deepcopier:"context"`
Email string `deepcopier:"force"`
}
func main() {
user := &User{
Name: "gilles",
Email: sql.NullString{
Valid: true,
String: "gilles#example.com",
},
}
resource := &UserResource{}
deepcopier.Copy(user).To(resource)
//copied from User's Name field
fmt.Println(resource.DisplayName)//output: gilles
fmt.Println(resource.Email) //output: gilles#example.com
fmt.Println(resource.MethodThatTakesContext) //output: hello from this method
}
Also, some other way you could achieve this is by encoding the source object to JSON and then decode it back to the destination object.
This is another possible answer
type Common struct {
Gender int
From string
To string
}
type Foo struct {
Id string
Name string
Extra Common
}
type Bar struct {
Id string
Name string
Extra Common
}
foo:=Foo{
Id:"123",
Name:"damitha",
Extra: struct {
Gender int
From string
To string
}{Gender:1 , From:"xx", To:"yy" },
}
bar:=*(*Bar)(unsafe.Pointer(&foo))
fmt.Printf("%+v\n",bar)
If you would like to copy or clone to a different struct, I would suggest using deepcopier
It provides nice features like skipping, custom mapping, and forcing.
You can achieve nested struct copy following way.
Install:
go get -u github.com/ulule/deepcopier
Example:
package main
import (
"fmt"
"strconv"
"github.com/ulule/deepcopier"
)
//FieldStruct - Field Struct
type FieldStruct struct {
Name string `deepcopier:"field:TargetName"`
Type string `deepcopier:"field:TargetType"`
}
//SourceStruct - Source Struct
type SourceStruct struct {
Name string `deepcopier:"field:TargetName"`
Age int `deepcopier:"field:TargetAge"`
StringArray []string `deepcopier:"field:TargetStringArray"`
StringToInt string `deepcopier:"context"`
Field FieldStruct
Fields []FieldStruct
}
//TargetFieldStruct - Field Struct
type TargetFieldStruct struct {
TargetName string
TargetType string
}
//TargetStruct - Target Struct
type TargetStruct struct {
TargetName string
TargetAge int
TargetStringArray []string
TargetInt int
TargetField TargetFieldStruct
TargetFields []TargetFieldStruct
}
//write methods
//TargetInt - StringToInt
func (s *SourceStruct) TargetInt() int {
i, _ := strconv.Atoi(s.StringToInt)
return i
}
func main() {
s := &SourceStruct{
Name: "Name",
Age: 12,
StringArray: []string{"1", "2"},
StringToInt: "123",
Field: FieldStruct{
Name: "Field",
Type: "String",
},
Fields: []FieldStruct{
FieldStruct{
Name: "Field1",
Type: "String1",
},
FieldStruct{
Name: "Field2",
Type: "String2",
},
},
}
t := &TargetStruct{}
//coping data into inner struct
deepcopier.Copy(&t.TargetField).From(&s.Field)
// copied array of Struct
for i := range s.Fields {
// init a struct
t.TargetFields = append(t.TargetFields, TargetFieldStruct{})
// coping the data
deepcopier.Copy(&t.TargetFields[i]).From(&s.Fields[i])
}
//Top level copy
deepcopier.Copy(t).From(s)
fmt.Println(t)
}
Output:
&{Name 12 [1 2] 123 {Field String} [{Field1 String1} {Field2 String2}]}