what does empty function name in go lang mean? [duplicate] - syntax

This question already has answers here:
What is this "err.(*exec.ExitError)" thing in Go code? [duplicate]
(2 answers)
Closed 7 years ago.
I am reading this code and I don't quite understand what line #2 does:
resp := route.Handler(req)
_, nilresponse := resp.(NilResponse)
if !nilresponse {
type NilResponse struct {
}
Thank you

This isn't an empty function name. This is a type-assertion. It is testing that resp is a NilResponse. If it is, then nilResponse will be true, otherwise it will be false. This code throws away the resulting type-asserted value by using _.
See Type Assertions.

If line two is _, nilresponse := resp.(NilResponse) then it's not a function call at all. It's a type assertion. The code is saying "the interface value represented by resp is of type NilResponse.
EDIT; your assignment is kind of odd though because the first return value would be the NilResponse object and the second (if specified) is a flag to indicate whether or not it worked (or maybe an error, can't remember if it's a bool or error). So typically it would be something like; nilResponse, ok := or nilResponse, err :=

Related

String type when using require.Equal in test [duplicate]

This question already has answers here:
Hiding nil values, understanding why Go fails here
(3 answers)
Closed 2 years ago.
My code is simply:
func Test_DecodeLBPolicy(t *testing.T) {
policy := decodeLBPolicy("lb:RING_HASH")
require.Equal(t, api.RING_HASH, policy.Type)
require.Equal(t, nil, decodeLBPolicy(""))
}
problem occurs at last line, the output is as below:
Error: Not equal:
expected: <nil>(<nil>)
actual : *api.LBPolicy(nil)
then I tried to replace expected "nil" to "*api.LBPolicy(nil)" it wont compile
but when I change the require to require.Equal(t, true, decodeLBPolicy("") == nil) it passed.
In go, an interface of value nil isn't equal to nil. This is because it has type information associated to it, whereas the nil keyword has no such type. (It also has type nil).
This explains theses lines
expected: <nil>(<nil>)
actual : *api.LBPolicy(nil)
You have a parameter of type *api.LBPolicy and of value nil. But you wanted a type niland value nil.
How to fix is a bit tricky, you could make sure that decodeLBPolicy really return nil and not a interface of value nil. Or compare to a interface of the good type and with the value nil. Or use the == trick as you showed
More details in this post: https://glucn.medium.com/golang-an-interface-holding-a-nil-value-is-not-nil-bb151f472cc7

What exactly is args ...interface{} means for a parameter of method? [duplicate]

This question already has answers here:
What does "..." mean when next to a parameter in a go function declaration?
(3 answers)
Closed 3 years ago.
I am referring to following method that takes last argument as args ...interfact{})
func (*sqlx.DB).Select(dest interface{}, query string, args ...interface{}) error
https://godoc.org/github.com/jmoiron/sqlx#DB.Select
From my understanding that the method accepts last parameter of any type which is variadic ..
So
selectStmt = 'Select * FROM users where user_id IN (?)'
selectStmt, userArgs, err := sqlx.In(selectStmt, userIDs)// userIDs is a slice
if err != nil {
return nil, errors.Wrap(err, "")
}
selectStmt = s.db.Rebind(selectStmt)
var users []User
err = s.db.Select(&users, selectStmt, userArgs) // wrong one .. Line A
err = s.db.Select(&users, selectStmt, userArgs... ) // right one .. Line B
In the aforementioned code if i comment out Line B , but not Line A it doesn't work. I get following error.
sql: converting argument $1 type: unsupported type []interface {}, a slice of interface *
Question
What exactly happening here , why can't go infer the variadic automatically ?? What is the need of passing extra '...' to the third argument?
What exactly happening here , why can't go infer the variadic automatically ?? What is the need of passing extra '...' to the third argument?
Go doesn't infer the variadic automatically - in fact, Go intentionally infers very little and does very little automatically. You need the ... because it does not infer. It also makes clear, when you pass a slice to a variadic, whether you mean for it to be exploded, or you mean for the slice itself to be a single argument; either could be a valid use case, and rather than making assumptions, Go expects you to be explicit.

What does "i.(string)" actually mean in golang syntax? [duplicate]

This question already has answers here:
Is this casting in golang?
(1 answer)
What is the meaning of "dot parenthesis" syntax? [duplicate]
(1 answer)
Closed 4 years ago.
I recently started looking for functional go examples and I found this function:
mapper := func (i interface{}) interface{} {
return strings.ToUpper(i.(string))
}
Map(mapper, New(“milu”, “rantanplan”))
//[“MILU”, “RANTANPLAN”]
Now in this function, as you can see the return value of mapper is:
strings.ToUpper(i.(string)).
But, what does this i.(string) syntax mean? I tried searching, but didn't find anything particularly useful.
i.(string) casts (or attempts at least) i (type interface{}) to type string. I say attempts because say i is an int instead, this will panic. If that doesn't sound great to you, then you could change the syntax to
x, ok := i.(string)
In this case if i is not a string, then ok will be false and the code won't panic.
i.(string) means converting i(interface{} type) to string type.

Get single result from multiple-context function call without intermediary variable [duplicate]

This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 6 years ago.
In Go I can use the underscore to ignore a return value from a function that returns multiple values. For instance:
res, _ := strconv.Atoi("64")
Suppose I wanted to use the first value directly into another function call (while ignoring error checking best practices, in this example):
myArray := make([]int, strconv.Atoi("64"))
The compiler will complain that I'm using a multiple-value function in a singe-value context:
./array-test.go:11: multiple-value strconv.Atoi() in single-value context
Is it possible to "pick and choose" from the return values in a single-line without resorting to auxiliary functions?
The only real way to do it is to create some utility "bypass" function, and since this is Go, you'll have to declare one per type.
for example:
func noerrInt(i int, e err) int {
return i
}
then you can do:
myArray := make([]int, noerrInt(strconv.Atoi("64")))
But really, this pretty much sucks, AND ignores best practices.

What is the meaning of "dot parenthesis" syntax? [duplicate]

This question already has answers here:
What exactly does .(data_type) method called/do?
(2 answers)
Is this casting in golang?
(1 answer)
Closed 2 years ago.
I am studying a sample Go application that stores data in mongodb. The code at this line (https://github.com/zeebo/gostbook/blob/master/context.go#L36) seems to access a user ID stored in a gorilla session:
if uid, ok := sess.Values["user"].(bson.ObjectId); ok {
...
}
Would someone please explain to me the syntax here? I understand that sess.Values["user"] gets a value from the session, but what is the part that follows? Why is the expression after the dot in parentheses? Is this a function invocation?
sess.Values["user"] is an interface{}, and what is between parenthesis is called a type assertion. It checks that the value of sess.Values["user"] is of type bson.ObjectId. If it is, then ok will be true. Otherwise, it will be false.
For instance:
var i interface{}
i = int(42)
a, ok := i.(int)
// a == 42 and ok == true
b, ok := i.(string)
// b == "" (default value) and ok == false

Resources