简单的代码却有三个结果,求助(使用goland V2020.1)
请大侠不吝赐教,先谢过。
代码如下(赋值粘贴到main.go即可运行):
package main
import (
“bufio”
“fmt”
“os”
“strings”
)
func main() {
var userInput = “”
go UserInput(&userInput)
for {
if “exit” == userInput {
fmt.Print(“程序退出”)
os.Exit(0)
}
}
}
func UserInput(userInput *string) {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print(“输入指令:”)
text, _ := reader.ReadString(‘\n’)
*userInput = strings.Replace(text, “\n”, “”, -1) // 去掉回车换行符
switch *userInput {
case “exit”: { // 退出本程序
return
}
default:
fmt.Println(“不可识别的指令”)
}
}
}
【1】通过“调试”按钮来运行程序:
输入exit并回车后,程序正常识别exit指令,程序正常退出。
【2】通过“运行”按钮来运行程序:
输入exit并回车后,显示下面结果(报告panic):
【3】通过终端,运行exe文件,显示下面结果(不能识别输入指令):
我的问题:
(1)为什么三种方式运行,会有三种结果?
(2)为什么“调试”模式运行,一切OK,而“运行”模式和“终端exe”模式都不对?特别是“终端exe”模式运行的结果,怎么会跑到switch的default分支去?
原因应该是指针变量的赋值不是原子操作,实验代码如下