Collection of Unique Functions in Go - pointers

I am trying to implement a set of functions in go. The context is an event server; I would like to prevent (or at least warn) adding the same handler more than once for an event.
I have read that maps are idiomatic to use as sets because of the ease of checking for membership:
if _, ok := set[item]; ok {
// don't add item
} else {
// do add item
}
I'm having some trouble with using this paradigm for functions though. Here is my first attempt:
// this is not the actual signature
type EventResponse func(args interface{})
type EventResponseSet map[*EventResponse]struct{}
func (ers EventResponseSet) Add(r EventResponse) {
if _, ok := ers[&r]; ok {
// warn here
return
}
ers[&r] = struct{}{}
}
func (ers EventResponseSet) Remove(r EventResponse) {
// if key is not there, doesn't matter
delete(ers, &r)
}
It is clear why this doesn't work: functions are not reference types in Go, though some people will tell you they are. I have proof, though we shouldn't need it since the language specification says that everything other than maps, slices, and pointers are passed by value.
Attempt 2:
func (ers EventResponseSet) Add(r *EventResponse) {
// ...
}
This has a couple of problems:
Any EventResponse has to be declared like fn := func(args interface{}){} because you can't address functions declared in the usual manner.
You can't pass a closure at all.
Using a wrapper is not an option because any function passed to the wrapper will get a new address from the wrapper - no function will be uniquely identifiable by address, and all this careful planning is for nought.
Is it silly of me to not accept defining functions as variables as a solution? Is there another (good) solution?
To be clear, I accept that there are cases that I can't catch (closures), and that's fine. The use case that I envision is defining a bunch of handlers and being relatively safe that I won't accidentally add one to the same event twice, if that makes sense.

You could use reflect.Value presented by Uvelichitel, or the function address as a string acquired by fmt.Sprint() or the address as uintptr acquired by reflect.Value.Pointer() (more in the answer How to compare 2 functions in Go?), but I recommend against it.
Since the language spec does not allow to compare function values, nor does it allow to take their addresses, you have no guarantee that something that works at a time in your program will work always, including a specific run, and including different (future) Go compilers. I would not use it.
Since the spec is strict about this, this means compilers are allowed to generate code that would for example change the address of a function at runtime (e.g. unload an unused function, then load it again later if needed again). I don't know about such behavior currently, but this doesn't mean that a future Go compiler will not take advantage of such thing.
If you store a function address (in whatever format), that value does not count as keeping the function value anymore. And if no one else would "own" the function value anymore, the generated code (and the Go runtime) would be "free" to modify / relocate the function (and thus changing its address) – without violating the spec and Go's type safety. So you could not be rightfully angry at and blame the compiler, but only yourself.
If you want to check against reusing, you could work with interface values.
Let's say you need functions with signature:
func(p ParamType) RetType
Create an interface:
type EventResponse interface {
Do(p ParamType) RetType
}
For example, you could have an unexported struct type, and a pointer to it could implement your EventResponse interface. Make an exported function to return the single value, so no new values may be created.
E.g.:
type myEvtResp struct{}
func (m *myEvtResp) Do(p ParamType) RetType {
// Your logic comes here
}
var single = &myEvtResp{}
func Get() EventResponse { return single }
Is it really needed to hide the implementation in a package, and only create and "publish" a single instance? Unfortunately yes, because else you could create other value like &myEvtResp{} which may be different pointers still having the same Do() method, but the interface wrapper values might not be equal:
Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.
[...and...]
Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.
The type *myEvtResp implements EventResponse and so you can register a value of it (the only value, accessible via Get()). You can have a map of type map[EventResponse]bool in which you may store your registered handlers, the interface values as keys, and true as values. Indexing a map with a key that is not in the map yields the zero value of the value type of the map. So if the value type of the map is bool, indexing it with a non-existing key will result in false – telling it's not in the map. Indexing with an already registered EventResponse (an existing key) will result in the stored value – true – telling it's in the map, it's already registered.
You can simply check if one already been registered:
type EventResponseSet map[*EventResponse]bool
func (ers EventResponseSet) Add(r EventResponse) {
if ers[r] {
// warn here
return
}
ers[r] = true
}
Closing: This may seem a little too much hassle just to avoid duplicated use. I agree, and I wouldn't go for it. But if you want to...

Which functions you mean to be equal? Comparability is not defined for functions types in language specification. reflect.Value gives you the desired behaviour more or less
type EventResponseSet map[reflect.Value]struct{}
set := make(EventResponseSet)
if _, ok := set[reflect.ValueOf(item)]; ok {
// don't add item
} else {
// do add item
set[reflect.ValueOf(item)] = struct{}{}
}
this assertion will treat as equal items produced by assignments only
//for example
item1 := fmt.Println
item2 := fmt.Println
item3 := item1
//would have all same reflect.Value
but I don't think this behaviour guaranteed by any documentation.

Related

Why does my interface not contain a value if I explicitly "associated"

Hey guys this code is part of a mock client, mock server interaction. I am having trouble understanding context.
Here I explicitly "associate" my tracker interface with context using 'WithValue' and then inject it into my request using WithContext. But when I check if my request's context contains the tracker interface I am returned the error "This context should contain a tracker" . What is it about context and WithValue that I am just not understanding?
var tracker Tracker
ctx := context.WithValue(context.Background(), contextKey, tracker)
req := httptest.NewRequest("GET", "localhost:12345/test", nil)
req.Header.Add(HEADER)
req = req.WithContext(ctx)
_, ok := ctx.Value(contextKey).(Tracker)
if !ok {
log.Fatal("1: This context should contain a tracker")
}
Tracker is an interface, and it's not set to anything, so it's nil. So, it can't change nil to a Tracker, so it fails.
https://play.golang.org/p/4-KQXlCR8vD
The problem isn't that tracker is nil, the problem is that it doesn't contain a value of a concrete type that implements Tracker. The value of tracker could be nil, and this would work, but it has to be a "typed" nil.
The type assertion fails, because type assertions and type switches only work when the instance being asserted has a concrete type. A value can be of a concrete type by declaration , assignment, type assertion , or a type switch case.
When you do the type assertion ctx.Value(contextKey).(Tracker)
There's (conceptually) a 2-step process to this:
Determine the ctx.Value(contextKey)'s concrete type.
Determine whether that concrete type implements Tracker.
Here's a playground example that hopefully illustrates this better: https://play.golang.org/p/ojYzLObkisd
The DoAny() function in there is emulating what is happening when you put your tracker into context and then try to retrieve it with the type assertion.
I know this is just a basic example, but it's not very good practice to use var something SomeInterfaceType, even if you do assign it a value. You should use concrete types for that. Or even better, just use type inference, and you won't have to worry about it. For example:
type Foo interface {
DoFoo() string
}
type MyFoo struct {}
func (f *MyFoo) DoFoo() string {
return "some foo value"
}
// not so good
var f Foo = new(MyFoo)
// good
var f *MyFoo = new(MyFoo)
// better
f := new(MyFoo)
This leverages the fact that interfaces are implicit in Go, and leads to much more obvious and maintainable code, especially in larger projects. Declaring a variable with an interface type is essentially making your variable poloymorphic, but the real power of interfaces isn't polymorphism. The real power is in using them as "functional requirements" for your package's exposed functions/methods. One rule that illustrates this really well is "Accept interfaces, return structs".
EDIT:
I've edited my original answer to correct some mistakes and make some improvements. I also would like to answer a follow-up question from the OP:
what I did not understand is that unless you have an object that utilizes that tracker's methods your interface is nil. Is this correct thinking?
I think what you're trying to say is correct, but the words used aren't quite right. First, there are no objects in Go, as it is not object-oriented. Where in OOP languages, objects hold instances of types, Go uses variables and constants to hold instances of types. So the concept exists, but not by the same name. So your tracker variable will be an instance of a type that satisfies your Tracker interface, but its value with be nil unless you assign it a non-nil instance of a type that satisfies the Tracker interface.

Pointers sent to function

I have following code in main():
msgs, err := ch.Consume(
q.Name, // queue
//..
)
cache := ttlru.New(100, ttlru.WithTTL(5 * time.Minute)) //Cache type
//log.Println(reflect.TypeOf(msgs)) 'chan amqp.Delivery'
go func() {
//here I use `cache` and `msgs` as closures. And it works fine.
}
I decided to create separate function for instead of anonymous.
I declared it as func hitCache(cache *ttlru.Cache, msgs *chan amqp.Delivery) {
I get compile exception:
./go_server.go:61: cannot use cache (type ttlru.Cache) as type *ttlru.Cache in argument to hitCache:
*ttlru.Cache is pointer to interface, not interface
./go_server.go:61: cannot use msgs (type <-chan amqp.Delivery) as type *chan amqp.Delivery in argument to hitCache
Question: How should I pass msg and cache into the new function?
Well, if the receiving variable or a function parameter expects a value
of type *T — that is, "a pointer to T",
and you have a variable of type T, to get a pointer to it,
you have to get the address of that variable.
That's because "a pointer" is a value holding an address.
The address-taking operator in Go is &, so you need something like
hitCache(&cache, &msgs)
But note that some types have so-called "reference semantics".
That is, values of them keep references to some "hidden" data structure.
That means when you copy such values, you're copying references which all reference the same data structure.
In Go, the built-in types maps, slices and channels have reference semantics,
and hence you almost never need to pass around pointers to the values of such types (well, sometimes it can be useful but not now).
Interfaces can be thought of to have reference semantics, too (let's not for now digress into discussing this) because each value of any interface type contains two pointers.
So, in your case it's better to merely not declare the formal parameters of your function as pointers — declare them as "plain" types and be done with it.
All in all, you should definitely complete some basic resource on Go which explains these basic matters in more detail and more extensively.
You're using pointers in the function signature but not passing pointers - which is fine; as noted in the comments, there is no reason to use pointers for interface or channel values. Just change the function signature to:
hitCache(cache ttlru.Cache, msgs chan amqp.Delivery)
And it should work fine.
Pointers to interfaces are nearly never used. You may simplify things and use interfaces of pass by value.

How to get properties of inherited structs in Go?

In Go,
type PacketType1 struct {
myValue string
}
type PacketType2 struct {
myValue2 string
}
Can I pass these generically and then check the type somehow? I looked into interfaces, however those seem to be for inheriting functions. Based on the names, this is for a packet system, how could I pass any of these packets to a function as an argument, check the type, and get properties of structs, etc. If this isn't possible, then how would I best implement a packet system in Go?
It is possible to pass the value as an interface{}, then use a type switch to detect which type was passed. Alternatively you can create an interface that exposes the common functionality you need and simply use that.
Interface and type switch:
func Example(v interface{}){
switch v2 := v.(type) {
case PacketType1:
// Do stuff with v1 (which has type PacketType1 here)
case PacketType2:
// Do stuff with v1 (which has type PacketType2 here)
}
}
Common interface:
type Packet interface{
GetExample() string
// More methods as needed
}
// Not shown: Implementations of GetValue() for all types used
// with the following function
func Example(v Packet) {
// Call interface methods
}
Which method is best for you depends on exactly what you are doing. If most of your types are similar with small differences one or more common interfaces are probably best, if they are quite different then a type switch may be better. Whichever one produces the shortest, clearest code.
Sometimes it is even best to use a mix of the two methods...

Generic value type of Go map [duplicate]

This question already has answers here:
generic map value
(2 answers)
Closed 11 months ago.
I am working on a web app with Go language. The respond(writer, html, *params) function needs a list of parameters which can be used to render an HTML page. I came up with a map as this which works fine:
&map[string][]string
However, recently I need to squeeze in a value pair in the format of {string, map[string][]string} which obviously blew up the compiler. So I am wondering if there is any generic type I can utilize, i.e. map[string]GenericType.
Any thoughts is welcomed.
So generally you store []string values for string keys. Most of the time. And once in a while you'd like to store a map[string][]string value for a string key.
First, drop the pointer from the map type: maps are already small descriptors, you can pass maps which will pass a copy of the descriptor and not the whole content, and if you add a new key-value pair to the copy, you will see that in the original. Passing a map by value is efficient and has the desired effect / working.
To be precise: map types are actually pointers to a map descriptor under the hood, but this is an implementation detail, you don't need to know this to use / work with maps. Only thing that matters is you can pass around map values efficiently.
Keeping only one map and being able to store values of both type []string and map[string][]string would require you to change the value type to interface{}, but then this would require you to use Type assertion every time you access an element in the params map, something like:
params := map[string]interface{}{}
params["a"] = []string{"b", "c"}
if list, ok := params["a"].([]string); ok {
fmt.Println(list)
}
Of course you could create a new type with map[string]interface{} being its underlying type, and add Get() and Set() methods for the most common value type []string, but instead I recommend a wrapper struct for the params, with multiple maps in multiple fields:
type Params struct {
P map[string][]string
M map[string]map[string][]string
}
Your code may use the map whichever has the value type that suits the value to be stored, for example:
params2 := Params{map[string][]string{}, map[string]map[string][]string{}}
params2.P["a"] = []string{"b", "c"}
params2.M["B"] = map[string][]string{
"x": []string{"X", "Y"},
}
fmt.Println(params2.P["a"])
fmt.Println(params2.M["B"])
You may also add Get() and Set() methods to Params that get and set elements from the most frequently used Params.P map.
Try it on the Go Playground.

How can I convert type dynamically in runtime in Golang?

Here is my example:
http://play.golang.org/p/D608cYqtO5
Basically I want to do this:
theType := reflect.TypeOf(anInterfaceValue)
theConvertedValue := anInterfaceValue.(theType)
The notation
value.(type)
is called a type-assertion. The type in an assertion has to be known at compile-time and it's always a type name.
In your playground example SetStruct2 could use a type-switch to handle different types for its second argument:
switch v := value.(type) {
case Config:
// code that uses v as a Config
case int:
// code that uses v as an int
}
You cannot, however, assert an interface to be something dynamic (like in your code). Because otherwise the compiler could not type-check your program.
Edit:
I don't want to case them one by one if there is another way to do so?
You can use reflection to work type-agnostically. You can then set stuff randomly on values but it will panic if you perform an illegal operation for a type.
If you want to benefit from the compiler's type checks you'll have to enumerate the different cases.

Resources