1 回答
TA贡献1828条经验 获得超13个赞
有时从 C++ OO 到 go-isms 的转变令人费解:P
这是任何在如何解决此类问题上遇到类似困难的人的工作代码。
/******************************************************************************
Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.
https://www.onlinegdb.com/online_c++_compiler
*******************************************************************************/
package main
import (
"fmt"
"errors"
"encoding/json"
)
type MHREQIF interface {
ProcessRequest(e int) (MHRESPIF, error)
}
type MHRESPIF interface {
SetResponse(err error)
}
type MHRSP struct {
MHRESPIF `json:"-"`
Success bool `json:"success"`
ErrorMessage string `json:"error_message,omitempty"`
}
type FooReq struct {
MHREQIF
Name string `json:"name"`
}
type FooRsp struct {
MHRSP
Name string `json:"name"`
}
func (self *MHRSP) SetResponse(err error) {
if err != nil {
self.Success = false
self.ErrorMessage = fmt.Sprintf("%v", err)
} else {
self.Success = true
}
}
func (self *FooReq) ProcessRequest(e int) (MHRESPIF, error) {
rsp := FooRsp{Name:self.Name}
if 0 == e {
return &rsp, nil
} else {
return &rsp, errors.New("crap")
}
}
func main() {
var msg_req MHREQIF
msg_req = &FooReq{Name:"bob"}
rsp, err := msg_req.ProcessRequest(1)
rsp.SetResponse(err)
msg_bytes, _ := json.Marshal(rsp)
msg_string := string(msg_bytes)
fmt.Println(msg_string)
}
- 1 回答
- 0 关注
- 135 浏览
添加回答
举报