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})
}
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
}
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")
}
}
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