M
M
Michael2017-02-06 12:48:47
go
Michael, 2017-02-06 12:48:47

How to understand this line in the code?

I'm looking at the documentation for the sessions module for martini here . And I don't quite understand this part:

v := session.Get("hello")
return v.(string)

v is a structure as I understand it. To refer to a field, I have to write v.name (for example). To call a method, I have to do v.name(), but what does v.(string) mean?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2017-02-06
@mak_ufo

v is an empty interface {} interface, which can contain absolutely any value of any data type. To get this value from there and use it, you need to cast it to the desired type.
v.(string) casts it to string. We can do this here, because we know that Get returns a string to us. If v does not contain a string, we will get a panic on the v.(string) line.
https://tour.golang.org/methods/15

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question