不声明结构体即可传递接口对象。

huangapple go评论98阅读模式
英文:

Pass interface object without declaring a struct

问题

如何在不声明结构体的情况下传递一个Interface{}对象?例如,当我使用Revel框架时,我想在特定情况下返回一个错误。

  1. 以下示例不起作用,我尝试了各种约定,但都没有成功,正确的方法是什么?

    return c.RenderJson(interface{"error":"xyz"})

  2. 如果我正在使用Revel框架构建服务器,向客户端返回错误的正确方法是什么?

英文:

How can I pass an Interface{} object without declaring a Struct?
for example when I'm using the Revel framework I want to return an error on a specific case.

  1. The following example is not working, I tried various conventions nothing worked, whats the right approach?

    return c.RenderJson(interface{"error":"xyz"})

  2. Whats the right approach to return an error to the Client if i'm building a Server with the Revel framework?

答案1

得分: 4

你不需要事先声明一个命名的struct类型,你可以直接使用:

return c.RenderJson(struct{ Error string }{"xyz"})
英文:

You don't have to declare a named struct type prior, you could simply use:

return c.RenderJson(struct{ Error string }{"xyz"})

答案2

得分: 4

  1. 尝试以下代码:
return c.RenderJson(map[string]string{"error": "xyz"})

RenderJson 接受一个接口类型的参数,这意味着你可以传递任何类型的数据。你不需要显式地将其转换为接口类型,但如果需要的话,可以这样做:

interface{}(map[string]string{"error": "xyz"})
  1. 我不确定,但我倾向于使用一个辅助函数来处理错误字符串(或错误类型)和状态码。
return HandleError(c, "xyz is not valid", 400)

然后 HandleError 函数会创建并写入错误信息。

如果你要处理一般性的错误,我不知道为什么不创建一个错误类型,例如:

type RequestError struct {
    Error       string `json:"error_message"`
    StatusCode  int    `json:"status_code"`
    ...
}
英文:

For 1. Try the following:

return c.RenderJson(map[string]string{"error": "xyz"})

RenderJson takes an interface, which means you can pass it anything. You don't need to explicitly cast to an interface, though that would be done like

interface{}(map[string]string{"error": "xyz"})

For 2. I am not certain, but I tend to have a helper function that takes the error string (or error type) and a status code and does the handling for me.

return HandleError(c, "xyz is not valid", 400)

And then HandleError just creates and writes the error.

If you are going to be handling errors in general, I don't know why you wouldn't make an error type though,

type RequestError struct {
    Error string `json:"error_message"`,
    StatusCode int `json:"status_code"`,
    ...
}

huangapple
  • 本文由 发表于 2015年3月3日 04:14:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/28818680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定