structure pointer field on a map in Golang [closed] - go

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 months ago.
Improve this question
I want to include different structure pointer fields in the map as shown below. (Of course the code below doesnt work)
type StructA struct {
}
type StructB struct {
}
mymap := map[string]*struct{}{
"StructA": StructA,
"StructB": StructB,
}

As #icza said the element type of a map must be a specific type. But this could be an interface that can store an object of different types. The type any (an alias for interface{} is in some ways like a pointer (though it also stores type info), so you could just do:
mymap := map[string]inteface{}{
"StructA": StructA{},
"StructB": StructB{},
}
To be a little safer you can restrict the types that can be added to the map to just the two structs. To do this you need an interface which specifies a function that both the struct types implement.
type (
Common interface{ ImplementsCommon() }
A struct{}
B struct{}
)
func (A) ImplementsCommon() {}
func (B) ImplementsCommon() {}
mymap := map[string]Common{
"A": A{},
"B": B{},
}
Try it on the Go Playground

Related

Multiple receivers on a single method [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Is it possible to have multiple receivers on a single function? In other words, a single function can belong to two or more structs?
Say I have
type Struct1 struct {
foo.Client
}
func CreateClient() struct1 {
return struct1{
ClientID: cId,
// ...
}
}
func (s *Struct1) MyFunc( // ... ) {}
But I also want to be able to associate MyFunc with another struct (different package):
type Struct2 struct {
lgr log.logger
}
func NewStruct2 (l *log.logger) (*Struct2, err) {
return &Struct2{mylog: *l}, nil
}
So what I want to actually have is:
func (s1 *Struct1, s2 *Struct2) MyFunc( // ... ) {}
"Is it possible to have multiple receivers on a single function?" -- It is not possible.
https://golang.org/ref/spec#Method_declarations
The receiver is specified via an extra parameter section preceding the
method name. That parameter section must declare a single non-variadic
parameter, the receiver.

Invalid receiver type with maps [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm trying to define additional methods on a basic map https://play.golang.org/p/3BKgxVJIjP1:
type Typ struct {
config string
}
type typeRegistry = map[string]Typ
func (r typeRegistry) Add(name string) {
typ := Typ{
config: "config",
}
r[name] = typ
}
Doing so fails:
invalid receiver type map[string]Typ (map[string]Typ is not a defined type)
Before refactoring the approach was similar but with a func instead of Typ:
type typeRegistry map[string]func()
func (r typeRegistry) Add(name string, factory func()) {
r[name] = factory
}
This version worked. Where is the difference in defining additional methods on map-type receivers?
type typeRegistry = map[string]Typ
Is a type alias. You cannot define methods on aliases (only on the original type--but in this case map[string]Typ cannot have methods on it, so you're out of luck).
What you probably want is to create a custom type, not an alias:
type typeRegistry map[string]Typ
Then your methods will work.

Go newbie: Getting "mismatched types *int and int" error when trying to compare reference to static integer [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm learning Go and trying to use reference to integer value in if-clause.
package main
import (
"fmt"
)
func main() {
a := 19
b := &a
if b > 10 {
fmt.Println("Its bigger")
}
}
This gives error message for type mismath.
How could I successfully compare value which b is referencing. In my training code I'm reading command line arguments with flags, but I suppose this example is reprex.
How should I compare when havin only reference available?
Here b is a pointer of int means *int. You can't compare *int type with int type.
Use *b to dereference to get the value and then compare with constant value.
if *b > 10 {
fmt.Println("Its bigger")
}

Protobuf/Go cannot use literal * (type *) as type * in array or slice literal [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have a struct in my generated proto file that looks like this (simplified):
type Record struct {
Field1 int64 `protobuf:"varint,1,opt,name=field1,proto3" json:"field1,omitempty"`
Field2 []byte `protobuf:"bytes,2,opt,name=field2,proto3" json:"field2,omitempty"`
}
and I'm trying to call it in my Go file
func foo(c messagepb.MessageServiceClient){
fmt.Println("Starting to send message...")
msgs := []*messagepb.MessageRequest{
recordpb.Record{ //error msg here
Field1: 1,
Field2: []byte{byte('a')},
}
}
...
}
but I get this error at the recordpb.Record line:
cannot use recordpb.Record literal (type recordpb.Record) as type *messagepb.MessageRequest in array or slice literal
If it helps, here's my messagepb:
message.proto
message MessageRequest { recordpb.Record records = 1; }
message.pb.go
type MessageRequest struct {
Record *recordpb.Record `protobuf:"bytes,1,opt,name=record,proto3" json:"record,omitempty"`
}
I can't find anything useful about why this is happening... Any ideas?
Looks like you are creating a slice of []*messagepb.MessageRequest and then adding a recordpb.Record to it. recordpb.Record is not the same type as *messagepb.MessageRequest.
Given this type
type MessageRequest struct {
Record *recordpb.Record `protobuf:"bytes,1,opt,name=record,proto3" json:"record,omitempty"`
}
It looks like your msgs var should be
msgs := []*messagepb.MessageRequest{
{
Record: &recordpb.Record{
Field1: 1,
Field2: []byte{byte('a')},
},
},
}
#mkopriva 's comments above add some nice explanation to this.

Struct declaration in Golang [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Given Go is largely based on C, and structs in that language are defined like this:
struct Person{...}
Why do we have the extra word in Go?
type Person struct{...}
Why do we need to mention both type and struct? Seems a little verbose.
All top-level statements in Go begin with a keyword indicating the type of declaration: package, import, type, var, const, or func, per the Go specification. As to why those decisions were made, you would need to ask those who made them, i.e. the Go maintainers.
Because both type and struct are significant here. You are defining a type with a keyword type. Your type could be anything, all of the following are valid
type MyBool bool
type MyInt int
type StringList []string
type StringListPointer *StringList
And to define a type that contains more than one value, you use the struct keyword.
type MyStruct struct {
x MyInt
y StringList
next *MyStruct
}
And you could, technically, have a struct without defining a type. This is not used very often, but it does have its use cases where you only intend to use a particular struct once. This is valid.
x := struct {
Name string
Value int
}{"Hello World!", 10}
fmt.Printf("%+v\n", x)
Consistency. The type keyword is used in all type definitions, and a defined type's underlying type needs not be a struct. Example:
type Fahrenheit int
Why would the language's designers make an exception for structs in Go's syntax?

Resources