duanjiaonie6097
2016-08-03 07:10
浏览 476
已采纳

如何用Go语言在另一个函数中调用一个函数?

I'm getting an error saying "undefined isvalid". How do I call another function in a function?

package main

import "fmt"

type Position struct {
    row int
    col int
}

func (posstn Position) isvalid() bool {
    if posstn.row > 8 || posstn.row < 0 || posstn.col > 8 || posstn.col < 0 {
        return false
    }
    return true
}

func Possmov(pos Position) {
    var isval isvalid
    if isval == true {
        fmt.Println("Something")
    }
}

func main() {
    Possmov(Position{1, 7})
}
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongpa5277 2016-08-03 07:19
    已采纳

    you may call isvalid() like this pos.isvalid() see this working sample code:

    package main
    
    import "fmt"
    
    type Position struct {
        row int
        col int
    }
    
    func (posstn Position) isvalid() bool {
        if posstn.row > 8 || posstn.row < 0 || posstn.col > 8 || posstn.col < 0 {
            return false
        }
        return true
    }
    
    func Possmov(pos Position) {
        isval := pos.isvalid()
        if isval == true {
            fmt.Println("Something")
        }
    }
    func main() {
        Possmov(Position{1, 7}) //Something
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douche3244 2016-08-03 07:17

    Your defined var isval isvalid, while isvalid is not a known type in Go, instead:

    func Possmov(pos Position) {
    
        var isval bool  // default is false
    
        if isval == true {
    
            fmt.Println("Something")
    
        }
    
    }
    

    https://play.golang.org/p/Ml2PgEOZfV

    评论
    解决 无用
    打赏 举报
  • douping3860 2016-08-03 07:55

    Your first line in function Possmov(pos Position){...} i.e. var isval isvalid is actually attempting to declare a variable of type isvalid (which is undefined as described by the error)

    Instead your isvalid() method is declared on the Position type.

    Try: var isvalid = pos.isvalid() in it's place

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题