duanhong8839 2015-09-18 15:52
浏览 15
已采纳

使用结构,地图还是其他?

I am new to Go ( and programming to an extent), so using a learn as you practice approach.

For the code below ( which pulls weather forecast ), I am looking to populate the longitude and latitude from a list I have.

I am not entirely sure how to setup that list in the first place - use structs and then pipe the value of the stored struct into this code? I tried that and it seems I can only hold one lon/lat pair in a struct. I was thinking of using maps but couldn't figure out how to set it all up. Perhaps, I should store the list of values in a text file and read from there:

p := Place{
    placeName: "Accra", lat: "43.6595", long: "-79.3433",
    placeName: "Kumasi", lat: "43.6595", long: "-79.3433",
    placeName: "Tamale", lat: "43.6595", long: "-79.3433",
}

f, err := forecast.Get(key, p.lat, p.long, "now", forecast.CA)
if err != nil {
    log.Fatal(err)
}

the struct looked like this ( I have about 10 separate long/lat values to use)

type Place struct {
    placeName string
    lat       string
    long      string
}
  • 写回答

1条回答 默认 最新

  • dtd5644 2015-09-18 18:03
    关注

    The Place struct is a single object, it has three properties, a name and lat and long. In order to have more than one you have to instantiate them individually, and commonly, you'd store them in a collection. In Go, the sensible choices would be an array, slice, or map.

    Here is an example using a slice. The syntax for array is roughly the same. If you'd like I can provide an example that uses a map after I return from lunch. One other thing to note is that I'm allocating the collection using a syntax referred to as 'composite literal' there are other ways to do this... I could use the append method or more conventional assignment to indexes/keys like myArray[0] = instanceOfPlaceThatIsAlreadyInitialized.

    places := []Place{
            Place{placeName: "Accra", lat: "43.6595", long: "-79.3433"},
            Place{placeName: "Kumasi", lat: "43.6595", long: "-79.3433"},
            Place{placeName: "Tamale", lat: "43.6595", long: "-79.3433"},
        }
    

    Extended example; https://play.golang.org/p/EHBgn_I9dA

    EDIT: Same thing with a map;

    places := map[string]Place{
            "Accra":Place{placeName: "Accra", lat: "43.6595", long: "-79.3433"},
            "Kumasi":Place{placeName: "Kumasi", lat: "43.6595", long: "-79.3433"},
            "Tamale": Place{placeName: "Tamale", lat: "43.6595", long: "-79.3433"},
        }
    

    https://play.golang.org/p/1A45-Z6k7q

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable