赞
踩
- import "fmt"
-
- func main() {
-
- //var x interface{} =func(x int)string{
-
- // return fmt.Sprintf("d:%d",x)
-
- //}
-
- //
-
- //switch v:=x.(type) { // 局部变量v是类型转换后的结果
-
- //case nil:
-
- // println("nil")
-
- //case*int:
-
- // println(*v)
-
- //case func(int)string:
-
- // println(v(100))
-
- //case fmt.Stringer:
-
- // fmt.Println(v)
-
- //default:
-
- // println("unknown")
-
- //}
-
- var x interface{} = func(x int) string {
-
- return fmt.Sprintf("d:%d", x)
-
- }
-
- switch v := x.(type) {
-
- case nil:
-
- println("nil")
-
- case *int:
-
- print(*v)
-
- case func(int) string:
-
- println(v(100))
-
- case fmt.Stringer:
-
- fmt.Println(v)
-
- default:
-
- print("unkown")
-
- }
-
- type MyIntergace interface{
-
- MyWriterFunc()
-
- MyReaderFunc()
-
- }
-
- type MyStrs struct{
-
- name string
-
- age int
-
- }
-
-
-
- func (in *MyStrs) MyWriterFunc(){
-
- fmt.Printf("MyWriterFunc")
-
- }
-
- func (in *MyStrs) MyReaderFunc(){
-
- fmt.Printf("MyReaderFunc")
-
- }
-
- var myvar MyIntergace=&MyStrs{
-
- name:"ssds",
-
- age:13
-
- }
-
- myvar.MyWriterFunc()
-
- myvar.MyReaderFunc()
-
- }
报错:
.\test_interface.go:49:34: syntax error: unexpected { at end of statement
.\test_interface.go:57:9: syntax error: unexpected newline in composite literal; possibly missing comma or }
.\test_interface.go:59:2: syntax error: non-declaration statement outside function body
错误点1: 需要将结构体定义部分移除main外
因为Go 语言要求所有类型、函数和方法的声明都必须在它们被使用之前进行。换句话说,你不能在 main 函数中引用一个还没有被声明的类型或函数。
因此,你需要将所有的类型声明(比如 MyInterface 和 MyStrs)、方法声明以及变量声明都放在 main 函数之前。这样,当 main 函数开始执行时,所有的依赖项都已经准备好了。
(虽然将interface定义防在main中也跑的通,但是最好还是将其放在main外,保持代码风格一致)
错误点2,结构体的每个字段及其值后面都需要加“,”,主要是为了划分字段的界限,指明字段名的开始
- var myvar MyInterface = &MyStrs{
- name: "ssds",
- age: 13,
- }
因此 纠正后的代码是:
- package main
-
- import "fmt"
-
- type MyStrs struct {
- name string
- age int
- }
- type Myinterface interface {
- MyWriterFunc()
- MyReaderFunc()
- }
-
- func (in *MyStrs) MyWriterFunc() {
- fmt.Printf("MyWriterFunc")
- }
- func (in *MyStrs) MyReaderFunc() {
- fmt.Printf("MyReaderFunc")
- }
- func main() {
- //var x interface{} =func(x int)string{
- // return fmt.Sprintf("d:%d",x)
- //}
- //
- //switch v:=x.(type) { // 局部变量v是类型转换后的结果
- //case nil:
- // println("nil")
- //case*int:
- // println(*v)
- //case func(int)string:
- // println(v(100))
- //case fmt.Stringer:
- // fmt.Println(v)
- //default:
- // println("unknown")
- //}
-
- var x interface{} = func(x int) string {
- return fmt.Sprintf("d:%d", x)
-
- }
- switch v := x.(type) {
- case nil:
- println("nil")
- case *int:
- print(*v)
- case func(int) string:
- println(v(100))
- case fmt.Stringer:
- fmt.Println(v)
- default:
- print("unkown")
- }
-
- var myvar Myinterface = &MyStrs{
- name: "ssds",
- age: 13,
- }
- myvar.MyWriterFunc()
- myvar.MyReaderFunc()
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。