default-interface-member
全部标签 我不确定为什么以下转换不起作用:import"fmt"funcmain(){v:=map[string]interface{}{"hello":"world"}checkCast(v)}funccheckCast(vinterface{}){_,isCorrectType:=v.(map[string]string)if!isCorrectType{fmt.Printf("incorrecttype") 最佳答案 map[string]interface{}与map[string]string不同。interface{}类型与str
我不确定为什么以下转换不起作用:import"fmt"funcmain(){v:=map[string]interface{}{"hello":"world"}checkCast(v)}funccheckCast(vinterface{}){_,isCorrectType:=v.(map[string]string)if!isCorrectType{fmt.Printf("incorrecttype") 最佳答案 map[string]interface{}与map[string]string不同。interface{}类型与str
运行时间https://play.golang.org/p/sl12vfS9vPpackagemainimport"fmt"funcmain(){err:=run()iferr!=nil{fmt.Printf("%#v",err)}}funcrun()(errerror){returncheck()}funccheck()*Result{returnnil}typeResultstruct{messagestring}func(result*Result)Error()string{returnresult.message} 最佳答案
运行时间https://play.golang.org/p/sl12vfS9vPpackagemainimport"fmt"funcmain(){err:=run()iferr!=nil{fmt.Printf("%#v",err)}}funcrun()(errerror){returncheck()}funccheck()*Result{returnnil}typeResultstruct{messagestring}func(result*Result)Error()string{returnresult.message} 最佳答案
我想将一个指向某个东西的指针传递给一个函数,在编译时不知道它的类型,让函数写入它。这是我认为可行的方法:funcfoo(destinterface{}){switch(dest).(type){case*int:fmt.Println("gotint")*dest=1//handleothercases...}}但是,使用*int输入调用它funcmain(){bar:=2foo(&bar)fmt.Println(bar)//expect1}产生编译错误dest的间接指令无效(类型接口(interface){})。我在这里做错了什么? 最佳答案
我想将一个指向某个东西的指针传递给一个函数,在编译时不知道它的类型,让函数写入它。这是我认为可行的方法:funcfoo(destinterface{}){switch(dest).(type){case*int:fmt.Println("gotint")*dest=1//handleothercases...}}但是,使用*int输入调用它funcmain(){bar:=2foo(&bar)fmt.Println(bar)//expect1}产生编译错误dest的间接指令无效(类型接口(interface){})。我在这里做错了什么? 最佳答案
我打算创建一个util函数,它将读取请求/响应的主体并将其返回。这是我目前所做的:funcGetBody(ininterface{})[]byte{varbodyio.ReadervarstatusCodeintswitchv:=in.(type){case*http.Request,*http.Response:body=v.BodystatusCode=v.StatusCodedefault:log.Fatal("Onlyhttp.Requestandhttp.Responseparameterscanbeacceptedtoparsebody")}ifstatusCode!=20
我打算创建一个util函数,它将读取请求/响应的主体并将其返回。这是我目前所做的:funcGetBody(ininterface{})[]byte{varbodyio.ReadervarstatusCodeintswitchv:=in.(type){case*http.Request,*http.Response:body=v.BodystatusCode=v.StatusCodedefault:log.Fatal("Onlyhttp.Requestandhttp.Responseparameterscanbeacceptedtoparsebody")}ifstatusCode!=20
我从简单的界面开始:typeModuleinterface{Init(deps...interface{})error}我想,实现会非常简单,因为这个方法应该匹配任意数量的提供参数。这就是我最终得到的这段代码,我想,TestModule实现了Module接口(interface)。typeTestModulestruct{}func(m*TestModule)Init(strstring)error{returnnil}但是当我想将TestModule传递给任何需要Module的函数时,我得到这个错误:cannotusemodule(type*TestModule)astypeModu
我从简单的界面开始:typeModuleinterface{Init(deps...interface{})error}我想,实现会非常简单,因为这个方法应该匹配任意数量的提供参数。这就是我最终得到的这段代码,我想,TestModule实现了Module接口(interface)。typeTestModulestruct{}func(m*TestModule)Init(strstring)error{returnnil}但是当我想将TestModule传递给任何需要Module的函数时,我得到这个错误:cannotusemodule(type*TestModule)astypeModu