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

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.

Related

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

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 :=

What do the brackets after func mean in Go? [duplicate]

This question already has answers here:
Function declaration syntax: things in parenthesis before function name
(3 answers)
Closed 10 months ago.
As a Go beginner, I stumbled across code where there are brackets directly after func
func (v Version) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}
So what does (v Version) mean?
This is not a function but a method. In this case, it adds the MarshalJSON method to the Version struct type.
The v is the name for the received value (and would be analogous to this in a Java method or self in Python), the Version specifies the type we're adding the method to.
See go by example for, well, an example, and the specification for more details.

"wrap it in a bufio.NewReader if it doesn't support ReadByte" pattern [duplicate]

This question already has answers here:
What is this "err.(*exec.ExitError)" thing in Go code? [duplicate]
(2 answers)
Closed 7 years ago.
Following is a snippet from one of the Go libs. Could anyone please point out the significance of r.(byteReader)? The syntax usage is not very obvious to a novice. byteReader is a defined interface and does not seem to be the member of io.Reader. Since, this seems to be some kind of nifty code, can anyone provide some insight.
The author mentions: "wrap it in a bufio.NewReader if it doesn't support ReadByte" pattern. https://github.com/dave-andersen/deltagolomb/blob/master/deltagolomb.go
type byteReader interface {
io.Reader
ReadByte() (c byte, err error)
}
func makeReader(r io.Reader) byteReader {
if rr, ok := r.(byteReader); ok {
return rr
}
return bufio.NewReader(r)
}
r.(byteReader) is called a type assertion. Even if io.Reader doesn't implement the byteReader interface in itself, it it still possible that the value stored in r might implement byteReader. So, by doing the type assertion, you can assert if that is the case:
The specification states:
x.(T) asserts that x is not nil and that the value stored in x is of
type T. The notation x.(T) is called a type assertion.
...
If T is
an interface type, x.(T) asserts that the dynamic type of x implements
the interface T.
Edit
The comment, "wrap it in a bufio.NewReader", refers to makeReader's provided io.Reader; if it doesn't implement byteReader, makeReader will wrap it in a bufio.Reader which does implement bytesReader, and return it instead.

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

What is this "err.(*exec.ExitError)" thing in Go code? [duplicate]

This question already has answers here:
What exactly does .(data_type) method called/do?
(2 answers)
What is the meaning of "dot parenthesis" syntax? [duplicate]
(1 answer)
What is err.(*os.PathError) in Go?
(2 answers)
Explain Type Assertions in Go
(3 answers)
Closed 10 months ago.
For instance, in this answer:
https://stackoverflow.com/a/10385867/20654
...
if exiterr, ok := err.(*exec.ExitError); ok {
...
What is that err.(*exec.ExitError) called? How does it work?
It's type assertion. I can't explain it better than the spec.
It's a type assertion. That if statement is checking if err is also a *exec.ExitError. The ok let's you know whether it was or wasn't. Finally, exiterr is err, but "converted" to *exec.ExitError. This only works with interface types.
You can also omit the ok if you're 100000 percent sure of the underlying type. But, if you omit ok and it turns out you were wrong, then you'll get a panic.
// find out at runtime if this is true by checking second value
exitErr, isExitError := err.(*exec.ExitError)
// will panic if err is not *exec.ExitError
exitErr := err.(*exec.ExitError)
The ok isn't part of the syntax, by the way. It's just a boolean and you can name it whatever you want.

Resources