[Go] Get used to return (*SomeType, error) as function return type
package main
import (
"fmt"
"log"
"strconv"
"strings"
)
type Point struct {
x int
y int
}
type Line struct {
p1 *Point
p2 *Point
}
func getInput() string {
return `0,9 -> 5,9
8,0 -> 0,8
9,4 -> 3,4
2,2 -> 2,1
7,0 -> 7,4
6,4 -> 2,0
0,9 -> 2,9
3,4 -> 1,4
0,0 -> 8,8
5,5 -> 8,2`;
}
func parsePoint(line string) (*Point, error) {
ps := strings.Split(line, ",");
x, err := strconv.Atoi(ps[0]);
if err != nil {
return nil, err
}
y, err := strconv.Atoi(ps[1]);
if err != nil {
return nil, err
}
return &Point{x, y}, nil
}
func parseLine(line string) (*Line, error) {
l := strings.Split(line, " -> ")
p1, err := parsePoint(l[0])
if err != nil {
return nil, err
}
p2, err := parsePoint(l[1])
if err != nil {
return nil, err
}
return &Line {
p1: p1,
p2: p2,
}, nil
}
func isHOrV (line Line) bool {
return line.p1.x == line.p2.x || line.p1.y == line.p2.y
}
func main() {
lines := []Line {}
for _, l := range strings.Split(getInput(), "\n") {
line, err := parseLine(l)
if err != nil {
log.Fatal("Cannot parse the line")
}
if isHOrV(*line) {
lines = append(lines, *line)
}
}
// Print each line with actual values of points
for _, line := range lines {
fmt.Printf("Line from (%d,%d) to (%d,%d)\n", line.p1.x, line.p1.y, line.p2.x, line.p2.y)
}
}
分类:
Go
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-02-19 [State Machine] Zag-js
2023-02-19 [React] React hook, component props for refactoring
2020-02-19 【逻辑思维】排中律:生存还是毁灭,只能选一个
2020-02-19 【逻辑思维】矛盾律:谁给理发师理发
2020-02-19 [AST Babel] Create a simple babel plugin
2020-02-19 [Angular 8 Unit testing] Testing a smart component with service injection -- 1
2019-02-19 [React] Ensure all React useEffect Effects Run Synchronously in Tests with react-testing-library