package main
import (
"fmt"
"bufio"
"os"
)
func main() {
fmt.Print("LOADED!\n")
fmt.Print("insert y value here: ")
inputY := bufio.NewScanner(os.Stdin)
inputY.Scan()
inputXfunc()
}
func inputXfunc() {
fmt.Print("insert x value here: ")
inputX := bufio.NewScanner(os.Stdin)
inputX.Scan()
slope()
}
func slope() {
fmt.Println(inputX.Text())
}
Run Code Online (Sandbox Code Playgroud)
每当我运行这个程序时,它说,inputX和inputY都是未识别的.如何使此程序使用所有函数都可访问的变量?我想做的就是通过inputX分配inputY然后打印出结果
我只是把我的评论作为答案......我建议不要这样做,但你可以在包范围内声明变量.它看起来像这样;
package main
import (
"fmt"
"bufio"
"os"
)
var inputX io.Scanner
func main() {
fmt.Print("LOADED!\n")
fmt.Print("insert y value here: ")
inputY := bufio.NewScanner(os.Stdin)
inputY.Scan()
inputXfunc()
}
func inputXfunc() {
fmt.Print("insert x value here: ")
inputX = bufio.NewScanner(os.Stdin) // get rid of assignment initilize short hand here
inputX.Scan()
slope()
}
func slope() {
fmt.Println(inputX.Text())
}
Run Code Online (Sandbox Code Playgroud)
但是,更好的选择是将方法定义更改为接受参数,并根据需要将值传递给它们.这就是这样;
func slope(inputX bufio.Scanner) {
fmt.Println(inputX.Text())
}
slope(myInputWhichIsOfTypeIOScanner)
Run Code Online (Sandbox Code Playgroud)