将结构体中的字符数组转换为字符串
时间:2024-02-09
浏览:460
作者:佚名
目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《将结构体中的字符数组转换为字符串》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~
问题内容
我有一个 struct 如下:
type tourdata struct {
artistid int //artist id
relationid string //key for relations
city string
country string
tourdates []string
}
type myrelation struct {
id int `json:"id"`
dateslocations map[string][]string `json:"dateslocations"`
}
其中包含来自 csv 文件的数据:
1,nagoya-japan,nagoya,japan, 1,penrose-new_zealand,penrose,new_zealand, 1,dunedin-new_zealand,dunedin,new_zealand, 2,playa_del_carmen-mexico,playa del carmen,mexico, 2,papeete-french_polynesia,papeete,french_polynesia,
myrelations 由 api 填充,其中包含:
"index": [
{
"id": 1,
"dateslocations": {
"dunedin-new_zealand": [
"10-02-2020"
],
"nagoya-japan": [
"30-01-2019"
],
"penrose-new_zealand": [
"07-02-2020"
]
}
},
{
"id": 2,
"dateslocations": {
"papeete-french_polynesia": [
"16-11-2019"
],
"playa_del_carmen-mexico": [
"05-12-2019",
"06-12-2019",
"07-12-2019",
"08-12-2019",
"09-12-2019"
]
}
}
日期来自另一个结构。我用来填充此结构的代码如下:
var onerecord tourdata
var allrecords []tourdata
for _, each := range csvdata {
onerecord.artistid, _ = strconv.atoi(each[0])
onerecord.relationid = each[1]
onerecord.city = each[2]
onerecord.country = each[3]
onerecord.tourdates = relations.index[onerecord.artistid-1].dateslocations[each[1]]
allrecords = append(allrecords, onerecord)
}
jsondata, err := json.marshal(allrecords) // convert to json
json.unmarshal(jsondata, &tourthings)
我需要将所有 1 组合在一起,然后是 2 等。我想创建另一个结构,并从这个结构中填充,但运气不佳 - 有什么想法吗?
为了澄清,我想说 tourdata.city 等于:
[nagoya,penrose,dunedin] [playa del carmen, papeete]
目前,如果我要打印 tourdata[0].city,我会打印 nagoya。
我尝试创建另一个结构体,并使用以下字段从 tourdata 结构体中填充:
type tourdataarrays struct {
artistid int
city []string
country []string
tourdates [][]string
}
然后使用以下代码填充结构:
var tourRecord TourDataArrays
var tourRecords []TourDataArrays
for i := 0; i < len(Relations.Index); i++ {
for j := 0; j < len(allRecords); j++ {
if allRecords[i].ArtistID == i+1 {
tourRecord.City = append(tourRecord.City, allRecords[j].City)
}
}
tourRecords = append(tourRecords, tourRecord)
}
但是,这会将所有城市添加到一个数组中,即
[名古屋、彭罗斯、达尼丁、卡门海滩、帕皮提]。
正确答案
如果我正确理解您的要求,您还需要将 city 声明为字符串数组。 (还有相应的国家/地区)。
查看此解决方案:https://go.dev/play/p/osgkbfWV3c5
请注意,我尚未从 Json 中的一个字段中删除国家/地区的重复数据并派生出城市和国家/地区。
终于介绍完啦!小伙伴们,这篇关于《将结构体中的字符数组转换为字符串》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
12.01
热门专题
