go - 在 Go 中表达函数的更好方法(结构方法)

标签 go methods struct

这是一个遍历点数组的函数。 Point 是一个结构,其元素 x 和 y 类型为 int。遍历函数是从另一个值为 dir 的函数调用的。可以避免循环开始时的 if 检查,因为一旦函数被调用,dir 值就不会改变。有没有更好的方式在 Go 中表达这个逻辑? struct 方法返回一个点。我提供了一个 struct 方法的示例。

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
}

最佳答案

因为 dir 在这里没有改变,那些 if 语句是多余的,你也应该在这种情况下使用 if-else 语句,因为["up", "down", "left", "right"] 中的一个可能发生。 首先看这个例子:

type Point struct {
    x int
    y int
}

func (p *Point) next_row() {
    p.x += 1
}

func main() {
    p := Point{0, 0}
    f := p.next_row

    for i := 0; i < 2; i++ {
        fmt.Println(p)
        f()
    }
    fmt.Println(p)
}

输出将是:

{0 0}
{1 0}
{2 0}

这里我们将接收器从 (p Point) 更改为 (p *Point) 因为我们想保存对 x 的影响并且。 根据这个假设,我们可以重写为:

type Point struct {
    x int
    y int
}

func (p *Point) next_row() {
    p.x += 1
}

func get_move(dir string) func() {
    var f func()
    switch dir {
    case "up":
        f = p.prev_row
    case "down":
        f = p.next_row
    case "left":
        f = p.prev_col
    case "right":
        f = p.next_col
    }
    return f
}

func trv_point(p Point, p_list []Point, dir string) int {
    seg_count := 0
    var nearby Point
    f := get_move(dir)
    for check_point_in_slice(p_list, p) {
        f()
        seg_count++
    }
    return seg_count
}

关于go - 在 Go 中表达函数的更好方法(结构方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71381894/

相关文章:

c++ - delete[ ] 会深度删除 C++ 中的结构吗?

去时间包常量而不是数字

c# - 在类和方法之间共享变量

java - 根据用户输入查找最大数字和最小数字(方法)

java - 引用另一个类作为实例变量?

c - 删除链表尾部的节点 C

go - 如何在 tcp 客户端中停止 io.Copy(file, conn)?

mongodb - 如何使用官方 MongoDB Go 驱动程序的 FindOne() 函数从 mongoDB 获取完整文档

go - 在go中列出和访问目录

swift - NSNotificationCenter 将结构作为 UserInfo 的一部分传递