When writing a Go program, you usually run the program in a black command line window. After the program execution is completed, the black window will usually close automatically. But sometimes, we may need to manually close the window after the program execution is completed. In this case, there are some tricks you can use to achieve this goal.
Add the "fmt.Scanln()" function after the last "fmt.Println" statement in the program. This will cause the program to pause execution before waiting for user input, wait for the user to press the "Enter" key, and then the program will continue execution and automatically close the command line window after the user presses the "Enter" key.
Here is an example:
package main import "fmt" func main() { fmt.Println("Hello, world!") fmt.Scanln() }
This program will print "Hello, world!" and wait for the user to press the "Enter" key.
In Go, you can use the "os/exec" package to execute a command and wait for the command to complete execution. We can use this package to start the "cmd.exe" process and pass the "/c" parameter and the command we want to run as arguments. We will then wait for the process to finish executing.
Here is an example:
package main import ( "fmt" "os/exec" ) func main() { cmd := exec.Command("cmd.exe", "/c", "pause") err := cmd.Run() if err != nil { fmt.Println(err) } }
This program will start the "cmd.exe" process and pass the "/c" parameter and the "pause" command. It will wait for the command to finish executing and display the message "Press any key to continue..." on the window. After the user presses any key, the window will automatically close.
You can use the system command "title" command to set the window title. In Go, you can use the "os/exec" package to execute this command.
Here is an example:
package main import ( "fmt" "os/exec" ) func main() { title := exec.Command("title", "My Program") err := title.Run() if err != nil { fmt.Println(err) } fmt.Println("Hello, world!") }
Running this program will display the "My Program" title on the window's title bar. When the program execution is completed, the window will automatically close.
Summary
The above are three methods on how to close the command line window in Go language. You can choose the method that suits you according to your needs. No matter which method you choose, they can help you run the Go program in a black command line window and close the window after the program is finished running, making your work more convenient and efficient.
The above is the detailed content of golang close black window. For more information, please follow other related articles on the PHP Chinese website!