我是接口的新手,并试图通过github做SOAP请求
我不明白的意思
Msg interface{}
Run Code Online (Sandbox Code Playgroud)
在这段代码中:
type Envelope struct {
Body `xml:"soap:"`
}
type Body struct {
Msg interface{}
}
Run Code Online (Sandbox Code Playgroud)
我观察到相同的语法
fmt.Println
Run Code Online (Sandbox Code Playgroud)
但不明白所取得的成就
interface{}
Run Code Online (Sandbox Code Playgroud) 我很熟悉在Go中,接口定义功能而不是数据.您将一组方法放入接口,但是您无法指定实现该接口的任何字段.
例如:
// Interface
type Giver interface {
Give() int64
}
// One implementation
type FiveGiver struct {}
func (fg *FiveGiver) Give() int64 {
return 5
}
// Another implementation
type VarGiver struct {
number int64
}
func (vg *VarGiver) Give() int64 {
return vg.number
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以使用接口及其实现:
// A function that uses the interface
func GetSomething(aGiver Giver) {
fmt.Println("The Giver gives: ", aGiver.Give())
}
// Bring it all together
func main() {
fg := &FiveGiver{}
vg := &VarGiver{3}
GetSomething(fg)
GetSomething(vg) …Run Code Online (Sandbox Code Playgroud) 我有一个功能
func doStuff(inout *interface{}) {
...
}
Run Code Online (Sandbox Code Playgroud)
此函数的目的是能够将任何类型的指针视为输入.但是,当我想用结构的指针调用它时,我有一个错误.
type MyStruct struct {
f1 int
}
Run Code Online (Sandbox Code Playgroud)
打电话的时候 doStuff
ms := MyStruct{1}
doStuff(&ms)
Run Code Online (Sandbox Code Playgroud)
我有
test.go:38: cannot use &ms (type *MyStruct) as type **interface {} in argument to doStuff
Run Code Online (Sandbox Code Playgroud)
我该如何投射&ms兼容*interface{}?
我有一个函数如下所示,它解码一些json数据并将其作为接口返回
package search
func SearchItemsByUser(r *http.Request) interface{} {
type results struct {
Hits hits
NbHits int
NbPages int
HitsPerPage int
ProcessingTimeMS int
Query string
Params string
}
var Result results
er := json.Unmarshal(body, &Result)
if er != nil {
fmt.Println("error:", er)
}
return Result
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试访问数据字段(例如Params)但由于某些原因它说接口没有这样的字段.知道为什么吗?
func test(w http.ResponseWriter, r *http.Request) {
result := search.SearchItemsByUser(r)
fmt.Fprintf(w, "%s", result.Params)
Run Code Online (Sandbox Code Playgroud) 我如何知道我可以从reply对象/接口访问的字段?我尝试过反射,但似乎你必须首先知道字段名称.如果我需要知道可用的所有字段怎么办?
// Do sends a command to the server and returns the received reply.
Do(commandName string, args ...interface{}) (reply interface{}, err error)
Run Code Online (Sandbox Code Playgroud) 我的目的是在两个响应结构的标头和正文中使用 HTTP 状态代码。但是,无需将状态代码设置两次作为函数参数,并再次设置结构以避免冗余。
response的参数JSON()是一个允许接受两个结构的接口。编译器抛出以下异常:
response.Status undefined (type interface {} has no field or method Status)
Run Code Online (Sandbox Code Playgroud)
因为响应字段不能有状态属性。有没有其他方法可以避免设置状态代码两次?
type Response struct {
Status int `json:"status"`
Data interface{} `json:"data"`
}
type ErrorResponse struct {
Status int `json:"status"`
Errors []string `json:"errors"`
}
func JSON(rw http.ResponseWriter, response interface{}) {
payload, _ := json.MarshalIndent(response, "", " ")
rw.WriteHeader(response.Status)
...
}
Run Code Online (Sandbox Code Playgroud)