如何更高效/紧凑地编写这个(冗长的)Golang代码?
我怎样才能把这个块写得更紧凑?我认为写这么简单的东西需要很多行代码如何更高效/紧凑地编写这个(冗长的)Golang代码?,go,Go,我怎样才能把这个块写得更紧凑?我认为写这么简单的东西需要很多行代码 // GetSegments Retrieve segments near given coordinate. func GetSegments(w http.ResponseWriter, r *http.Request) { near := r.FormValue("near") givenCoordinate := strings.Split(near, ",") lat, _ := strconv.Pars
// 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调用:
我真的很喜欢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
}
为什么要显式强制转换为float32?@favoretti:
strconv.ParseFloat
返回typefloat64
。not typefloat32
:func-ParseFloat(s字符串,位大小int)(f float64,err error)
。Go需要显式转换。@peterSO我知道,但我的意思是为什么不将坐标保持在float64
中呢。@favoretti可能float32
是API要求?@favoretti:float32
对于GPS坐标精度来说足够精确:。定义一个全局空的坐标{}合适吗
并在出现错误时返回该值,或者该值通常不可取(或无用)?@coredump,由于该值是通过堆栈返回的,因此不会更快/更节省内存。