This is a function to traverse an array of Points. A Point is a struct with elements x and y of type int. The traverse function is called from another function with a value of dir. The if check at the beginning of the loop can be avoided because the dir value, once the function is called, does not change. Is there a better way to express this logic in Go? The struct method returns a Point. I have provided one example of the struct method.
type Point struct {
x int
y int
}
func (p Point) next_row() Point {
nearby := Point{p.x + 1, p.y}
return nearby
}
func trv_point(p Point, p_list []Point, dir string) int {
seg_count := 0
var nearby Point
for {
if dir == "up" {
nearby = p.prev_row()
}
if dir == "down" {
nearby = p.next_row()
}
if dir == "left" {
nearby = p.prev_col()
}
if dir == "right" {
nearby = p.next_col()
}
if !check_point_in_slice(p_list, nearby) {
break
}
seg_count++
p = nearby
}
return seg_count
}