github.com/llvm-mirror/llgo@v0.0.0-20190322182713-bf6f0a60fce1/test/execution/interfaces/assert.go (about)

     1  // RUN: llgo -o %t %s
     2  // RUN: %t 2>&1 | FileCheck %s
     3  
     4  // CHECK: x is nil
     5  // CHECK-NEXT: i2v: 123456
     6  // CHECK-NEXT: !
     7  // CHECK-NEXT: (*X).F1: 123456
     8  
     9  package main
    10  
    11  type X struct{ x int }
    12  
    13  func (x *X) F1() { println("(*X).F1:", x.x) }
    14  func (x *X) F2() { println("(*X).F2") }
    15  
    16  type I interface {
    17  	F1()
    18  	F2()
    19  }
    20  
    21  func main() {
    22  	var x interface{}
    23  
    24  	// x is nil. Let's make sure an assertion on it
    25  	// won't cause a panic.
    26  	if x, ok := x.(int32); ok {
    27  		println("i2v:", x)
    28  	}
    29  	if x == nil {
    30  		println("x is nil")
    31  	}
    32  
    33  	x = int32(123456)
    34  
    35  	// Let's try an interface-to-value assertion.
    36  	if x, ok := x.(int32); ok {
    37  		println("i2v:", x)
    38  	}
    39  	if x, ok := x.(int64); ok {
    40  		println("i2v:", x)
    41  	}
    42  
    43  	// This will fail the assertion.
    44  	if i, ok := x.(I); ok {
    45  		i.F1()
    46  		_ = i
    47  	} else {
    48  		println("!")
    49  	}
    50  
    51  	// Assign an *X, which should pass the assertion.
    52  	x_ := new(X)
    53  	x_.x = 123456
    54  	x = x_ //&X{x: 123456}
    55  	if i, ok := x.(I); ok {
    56  		i.F1()
    57  		_ = i
    58  	} else {
    59  		println("!")
    60  	}
    61  }