@kjk1/

gobook interface type assertion

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.6625326432298142","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"Ly8gYWxsb3cgZXJyb3IKcGFja2FnZSBtYWluCgppbXBvcnQgKAoJImZtdCIKKQoKLy8gOnNob3cgc3RhcnQKZnVuYyBwcmludFR5cGVBbmRWYWx1ZShpdiBpbnRlcmZhY2V7fSkgewoJaWYgdiwgb2sgOj0gaXYuKHN0cmluZyk7IG9rIHsKCQlmbXQuUHJpbnRmKCJpdiBpcyBvZiB0eXBlIHN0cmluZyBhbmQgaGFzIHZhbHVlICclcydcbiIsIHYpCgkJcmV0dXJuCgl9CglpZiB2LCBvayA6PSBpdi4oaW50KTsgb2sgewoJCWZtdC5QcmludGYoIml2IGlzIG9mIHR5cGUgaW50IGFuZCBoYXMgdmFsdWUgJyVkJ1xuIiwgdikKCQlyZXR1cm4KCX0KCWlmIHYsIG9rIDo9IGl2LigqaW50KTsgb2sgewoJCWZtdC5QcmludGYoIml2IGlzIG9mIHR5cGUgKmludCBhbmQgaGFzIHZhbHVlICclcydcbiIsIHYpCgkJcmV0dXJuCgl9Cn0KCmZ1bmMgcGFuaWNPbkludmFsaWRDb252ZXJzaW9uKCkgewoJdmFyIGl2IGludGVyZmFjZXt9ID0gInN0cmluZyIKCgl2IDo9IGl2LihpbnQpCglmbXQuUHJpbnRmKCJ2IGlzIGludCBvZiB2YWx1ZTogJWRcbiIsIHYpCn0KCmZ1bmMgbWFpbigpIHsKCS8vIHBhc3MgYSBzdHJpbmcKCXByaW50VHlwZUFuZFZhbHVlKCJzdHJpbmciKQoJaSA6PSA1CgkvLyBwYXNzIGFuIGludAoJcHJpbnRUeXBlQW5kVmFsdWUoaSkKCS8vIHBhc3MgYSBwb2ludGVyIHRvIGludCBpLmUuICppbnQKCXByaW50VHlwZUFuZFZhbHVlKCZpKQoKCXBhbmljT25JbnZhbGlkQ29udmVyc2lvbigpCn0KCi8vIDpzaG93IGVuZA=="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// allow error
package main

import (
	"fmt"
)

// :show start
func printTypeAndValue(iv interface{}) {
	if v, ok := iv.(string); ok {
		fmt.Printf("iv is of type string and has value '%s'\n", v)
		return
	}
	if v, ok := iv.(int); ok {
		fmt.Printf("iv is of type int and has value '%d'\n", v)
		return
	}
	if v, ok := iv.(*int); ok {
		fmt.Printf("iv is of type *int and has value '%s'\n", v)
		return
	}
}

func panicOnInvalidConversion() {
	var iv interface{} = "string"

	v := iv.(int)
	fmt.Printf("v is int of value: %d\n", v)
}

func main() {
	// pass a string
	printTypeAndValue("string")
	i := 5
	// pass an int
	printTypeAndValue(i)
	// pass a pointer to int i.e. *int
	printTypeAndValue(&i)

	panicOnInvalidConversion()
}

// :show end