FAQ
Try using:
    interface{} //empty interface, instead of the IHello.
http://play.golang.org/p/J0KK2ZpAQQ
On Thursday, July 12, 2012 10:54:59 PM UTC-4, actberw wrote:

thinks, Chandra Sekar S
but i'm still wandering in which case, i can get (Z, false) .

在 2012年7月13日星期五UTC+8上午10时28分53秒,Chandra Sekar S写道:
What you're seeing is a compilation error, not a runtime panic. The code
does not compile because string type doesn't implement the Say method and
hence there is no way it can be an IHello.

--
Chandra Sekar.S


On Thu, Jul 12, 2012 at 7:28 PM, actberw <act...@gmail.com <javascript:>>
wrote:
hi ,every one
recently i start learning go, in go language spec
http://golang.org/ref/spec#Type_assertions ,
it says :

If a type assertion is used in an assignment or initialization of the
form

v, ok = x.(T)
v, ok := x.(T)
var v, ok = x.(T)

the result of the assertion is a pair of values with types (T, bool).
If the assertion holds, the expression returns the pair (x.(T), true);
otherwise, the expression returns (Z, false) where Z is the zero value
<http://golang.org/ref/spec#The_zero_value> for type T. No run-time
panic occurs in this case. The type assertion in this construct thus
acts like a function call returning a value and a boolean indicating
success. (§Assignments <http://golang.org/ref/spec#Assignments>)

i did a test:

package main

import "fmt"

type IHello interface {

Say()

}

type Man struct {

name string

age int

}

func (man Man) Say() {

fmt.Printf("name is %s, age is %d\n", man.name, man.age)

}

func main() {

var man IHello = Man{name: "actberw", age: 23}

x, ok := man.(string) // x, ok := man.(Man) // this is correct

if ok {

x.Say()

} else {

fmt.Println("assert error!")

}

}

when i run, i got a error message:

impossible type assertion: man (type IHello) cannot have dynamic type
string (missing Say method)

I don't understand the "in which case no run-time panic occurs" means.

I expect ok is false and no run-time panic happens,what should i do?

os is: mac os lion

thanks.



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedJan 1, '15 at 5:15p
activeJan 1, '15 at 5:15p
posts1
users1
websitegolang.org

1 user in discussion

Rogerjd: 1 post

People

Translate

site design / logo © 2022 Grokbase