匿名函数相关

博客内容讲述了在解决Go语言刷题时遇到的语法错误,主要问题在于匿名函数的使用。作者指出,错误地将匿名函数直接用作值导致了编译错误。通过调整代码,将匿名函数定义为一个独立的函数,并进行调用,成功解决了问题。修正后的代码能正确地遍历二叉树并找到路径和目标和。

刷题遇到的语法错误
错误写法:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pathSum(root *TreeNode, targetSum int) (ans [][]int) {
    path := []int{}
    var dfs func(*TreeNode, int)
    
    dfs = func(node *TreeNode, left int) {
        if node == nil {
            return
        }
        left -= node.Val
        path = append(path, node.Val)
        defer func() { path = path[:len(path)-1] }()
        if node.Left == nil && node.Right == nil && left == 0 {
            //append([]int(nil), path...)实现了将path打散,然后传入新创建的切片[]int(nil)里
            //然后将这个切片传入ans这个二维切片里
            ans = append(ans, append([]int(nil), path...))
            return
        }
        dfs(node.Left, left)
        dfs(node.Right, left)
    }(root,targetSum)
    //dfs(root, targetSum)
    return
}

这么写:匿名函数后面加(参数),是调用了,然后前面又赋给dfs,所以匿名函数得有返回值,所以出现了报错:
Line 28: Char 6: (func literal)(root, targetSum) used as value (solution.go)

正确写法如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func pathSum(root *TreeNode, targetSum int) (ans [][]int) {
    path := []int{}
    var dfs func(*TreeNode, int)
    
    dfs = func(node *TreeNode, left int) {
        if node == nil {
            return
        }
        left -= node.Val
        path = append(path, node.Val)
        defer func() { path = path[:len(path)-1] }()
        if node.Left == nil && node.Right == nil && left == 0 {
            //append([]int(nil), path...)实现了将path打散,然后传入新创建的切片[]int(nil)里
            //然后将这个切片传入ans这个二维切片里
            ans = append(ans, append([]int(nil), path...))
            return
        }
        dfs(node.Left, left)
        dfs(node.Right, left)
    }
    dfs(root, targetSum)
    return
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值