在结构体(struct)或接口(interface)内部执行计算?

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

perform computation inside struct or interface?

问题

我正在构建一个要保存到MongoDB的数据。我从一个API得到了一个JSON响应,格式如下:

{
  coord: { lon: 20, lat: 30 }
  main:
      [
        {"temp":304.15,"pressure":1005,"humidity":74,"temp_min":304.15,"temp_max":304.15}
      ]
}

在main[0].temp、main[0].temp_min和main[0].temp_max中,值是以开尔文为单位的。我想在保存到MongoDB之前将其转换为摄氏度。

我可以创建一个简单的结构体,如下所示:

type Item struct {
  Temp string
  Pressure int
  Humidity int
  Temp_min string
  Temp_max string
}

但是我想在保存之前对Temp、Temp_min和Temp_max进行转换。除了将其赋值给变量,然后重新赋值之外,还有其他方法吗?这可以在接口中完成吗?

我对Go还不是很熟悉,但我正在学习,在使用Go构建一个Web应用程序。

英文:

I am constructing a Data to save to mongodb. I have a json response from an API like this

{
  coord: { lon: 20, lat: 30 }
  main:
      [
        {"temp":304.15,"pressure":1005,"humidity":74,"temp_min":304.15,"temp_max":304.15}
      ]
}

inside main[0].temp, main[0].temp_min, main[0].temp_max values are in kelvin. I want to convert it to do conversions to celsius before saving it mongodb.

I can make a simple struct like this:

type Item struct {
  Temp string
  Pressure int
  Humidity int
  Temp_min string
  Temp_max string
} 

but I want to do a conversion in Temp, Temp_min & Temp_max before saving it.. Is there other way rather than assigning it to variable, then reassigning?. can this be done in an Interface?

Im still not fluent in Go, but I am studying, while building a webapp in Go.

答案1

得分: 1

你如何初始化你的结构体?

如果你可以访问它的值,你可以在结构体初始化时进行转换,就像这样:

func NewItem() *Item {
    return &Item{convertToCelsius(temp), pressure, humidity, convertToCelsius(tempMin), convertToCelsius(tempMax)}
}

在这个例子中,NewItem 函数返回一个指向 Item 结构体的指针,结构体的各个字段通过调用 convertToCelsius 函数进行转换后进行初始化。

英文:

How do you initialize your structure?

If you have access to it's values, you can convert it during structure initialization, something like this:

func NewItem() *Item {
    return &Item{convertToCelsius(temp), pressure, humidity convertToCelsius(tempMin), convertToCelsius(tempMax)}
}

huangapple
  • 本文由 发表于 2014年7月5日 16:48:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/24584651.html
匿名

发表评论

匿名网友

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

确定