Go has any rules converting from empty interface type to other type?

2,013 views
Skip to first unread message

Jeyong

unread,
Jun 1, 2011, 6:15:34 PM6/1/11
to golang-nuts
I could not find empty interface type conversion rule for 2-days.

I want to do that.

package main
import "fmt"

type Any interface{}

func main() {
var a Any
a = 3
sum := a + 5
fmt.Println(sum)
}

But I got error message : prog.go:10: invalid operation: a + 5
(mismatched types Any and int

Now I find that

package main
import "fmt"

type Any interface{}

func main() {
var a Any
a = 3
sum := a.(int) + 5
fmt.Println(sum)
}
Is it correct grammar?

numeric type conversion rule is different.
ex)
var b int
var c float32
b = int(c)


Is it answer if I want to converting type?
empty_interface_var.(conversion_type)

And could you explain what it mean : empty_interface_var.(???)

Thank you. (I'm sorry that I'm good at English)

Kyle Lemons

unread,
Jun 1, 2011, 6:28:44 PM6/1/11
to Jeyong, golang-nuts
http://golang.org/doc/go_spec.html#Type_assertions

Type assertions are used to get a concrete type or another interface for the underlying value and do not actually change the value:
var a interface{} = 42
var b int = a.(int) / 2
The value 42 does not actually change, the type assertion is exactly what the name implies: an assertion that the variable is of the specified type (and a panic results if it isn't if you don't use the `, ok` notation).  Once it's been asserted, you use it as if it were that type; in this case, you can then assign it to an integer or even do math on it without issue.

Conversions actually change the type of the value and give you back an entirely new one:
var a int = int( 3.14 )
3.14 is not an int, so it has to be changed in order to be assigned to one.
--
~Kyle

"Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?" 
— Brian Kernighan

Jeyong

unread,
Jun 1, 2011, 8:52:58 PM6/1/11
to golang-nuts
Now I understand type assertion and type conversion.
Thank you!

On 6월2일, 오전7시28분, Kyle Lemons <kev...@google.com> wrote:
> http://golang.org/doc/go_spec.html#Type_assertionshttp://golang.org/doc/go_spec.html#Conversions
> *"Everyone knows that debugging is twice as hard as writing a program in the
> first place. So if you're as clever as you can be when you write it, how
> will you ever debug it?"
> — Brian Kernighan*
Reply all
Reply to author
Forward
0 new messages