如何编写这个(详细)Golang代码更有效率/紧凑?

问题描述:

我该如何写这个块更紧凑?我认为写很多简单的代码是很多的。如何编写这个(详细)Golang代码更有效率/紧凑?

// 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

我真的很喜欢围棋,但这是,如果我使用它的权利,我想知道的事情之一..

+0

为什么要显式转换为float32? – favoretti

+0

@favoretti:'strconv.ParseFloat'返回类型'float64'。不要键入'float32':'func ParseFloat(s string,bitSize int)(f float64,err error)'。 Go需要明确的转换。 – peterSO

+0

@peterSO我知道,但为什么不把坐标保存在'float64'中,这就是我的意思。 – favoretti

最重要的是你编写的代码能够产生正确的结果和有用的错误信息。检查错误。例如,

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 
} 
+0

定义一个全局空的'Coordinate {}'是否合适,并在错误的情况下返回它,或者它通常不可取(或无用)? – coredump

+0

@coredump,由于该值是通过堆栈返回的,因此它不会更快/更高的内存效率。 – kostya