Golang程序生成的exe文件无法打开怎么办
Golang程序生成的exe文件无法打开怎么办 我创建了一个随机选择字母的程序,但当我尝试用 .exe 文件启动它时,它会立即关闭,我该怎么办? 我正在使用 Geany 作为编辑器,目前正在学习这门语言,但我找不到任何可能有帮助的信息。 这是我的代码:
package main
import (
"math/rand"
"fmt"
"time"
)
func main (){
rand.Seed(time.Now().Unix())
prompts:=[]string{"hatred","a, b, c, d, e "}
fmt.Println("Ur prompt is: ", prompts[rand.Intn(len(prompts))])
}
更多关于Golang程序生成的exe文件无法打开怎么办的实战教程也可以访问 https://www.itying.com/category-94-b0.html
4 回复
你是如何启动它的?
这个简短的程序预期会向标准输出打印一些内容,然后退出。
更多关于Golang程序生成的exe文件无法打开怎么办的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
我对终端应用程序中点击这个概念不是很熟悉……
但或许可以添加一些“按任意键关闭”的提示?
这个程序不是为我设计的,用户应该通过点击exe文件来启动它,但当我这样做时,它立刻就关闭了。
你的程序运行后立即关闭是因为控制台程序执行完成后会自动退出。要解决这个问题,可以在程序末尾添加等待用户输入的代码。以下是修改后的示例:
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
prompts := []string{"hatred", "a, b, c, d, e "}
fmt.Println("Ur prompt is: ", prompts[rand.Intn(len(prompts))])
// 等待用户按回车键
fmt.Print("按回车键退出...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
或者使用更简单的方法:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
prompts := []string{"hatred", "a, b, c, d, e "}
fmt.Println("Ur prompt is: ", prompts[rand.Intn(len(prompts))])
// 等待用户输入
var input string
fmt.Scanln(&input)
}
另外,从Go 1.20开始,rand.Seed已被弃用,建议使用新的随机数生成方式:
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"time"
)
func main() {
// 使用新的随机数生成方式
r := rand.New(rand.NewSource(time.Now().UnixNano()))
prompts := []string{"hatred", "a, b, c, d, e "}
fmt.Println("Ur prompt is: ", prompts[r.Intn(len(prompts))])
// 等待用户按回车键
fmt.Print("按回车键退出...")
bufio.NewReader(os.Stdin).ReadBytes('\n')
}
编译并运行修改后的程序,控制台会保持打开直到你按下回车键。

