gpt4 book ai didi

go - 如何更高效/紧凑地编写此(详细)Golang 代码?

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:44 24 4
gpt4 key购买 nike

我怎样才能把这个 block 写得更紧凑?我认为写这么简单的东西需要很多行代码。

// GetSegments Retrieve segments near given coordinate.
func GetSegments(w http.ResponseWriter, r *http.Request) {
near := r.FormValue("near")
givenCoordinate := strings.Split(near, ",")

lat, _ := strconv.ParseFloat(givenCoordinate[0], 32)
lon, _ := strconv.ParseFloat(givenCoordinate[1], 32)

lat32 := float32(lat)
lon32 := float32(lon)

coord := Coordinate{
Latitude: lat32,
Longitude: lon32}

fmt.Println(coord)
}

此代码块通过 Web API 调用:
http://localhost:8080/segments?near=14.52872,52.21244

我真的很喜欢 Go,但这是我想知道我是否正确使用它的地方之一。

最佳答案

最重要的是您编写的代码可以产生正确的结果和有用的错误消息。检查错误。例如,

type Coordinate struct {
Latitude float32
Longitude float32
}

// GetSegments Retrieve segments near given coordinate.
// http://localhost:8080/segments?near=14.52872,52.21244
func GetSegments(w http.ResponseWriter, r *http.Request) (Coordinate, error) {
const fnc = "GetSegments"
near := r.FormValue("near")
if len(near) == 0 {
return Coordinate{}, fmt.Errorf("%s: near coordinates missing", fnc)
}
latlon := strings.Split(near, ",")
if len(latlon) != 2 {
return Coordinate{}, fmt.Errorf("%s: near coordinates error: %s", fnc, near)
}
lat, err := strconv.ParseFloat(latlon[0], 32)
if err != nil {
return Coordinate{}, fmt.Errorf("%s: near latitude: %s: %s", fnc, latlon[0], err)
}
lon, err := strconv.ParseFloat(latlon[1], 32)
if err != nil {
return Coordinate{}, fmt.Errorf("%s: near longitude: %s: %s", fnc, latlon[1], err)
}
coord := Coordinate{
Latitude: float32(lat),
Longitude: float32(lon),
}
fmt.Println(coord)
return coord, nil
}

关于go - 如何更高效/紧凑地编写此(详细)Golang 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32796959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com