Application fields of Go language in software development
With the continuous advancement and development of technology, more and more developers are beginning to pay attention to using Go language to develop software. development. Go language is a static compiled programming language developed by Google. It is efficient, concise and easy to learn, and is suitable for various application fields. This article will introduce the application fields of Go language in software development and provide specific code examples.
package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, World!") } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
The above code creates a simple HTTP server, listening on port 8080, and will return a "Hello, World!" response when there is a request.
package main import ( "fmt" "time" ) func printNumbers() { for i := 1; i <= 5; i++ { fmt.Println(i) time.Sleep(time.Second) } } func main() { go printNumbers() time.Sleep(5 * time.Second) }
The above code creates a goroutine to print numbers from 1 to 5, and the main program ends after waiting for 5 seconds. This can execute multiple tasks at the same time and improve the concurrency capability of the program.
package main import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "username:password@tcp(127.0.0.1:3306)/database") if err != nil { log.Fatal(err) } defer db.Close() rows, err := db.Query("SELECT id, name FROM users") if err != nil { log.Fatal(err) } var id int var name string for rows.Next() { err := rows.Scan(&id, &name) if err != nil { log.Fatal(err) } fmt.Printf("ID: %d, Name: %s ", id, name) } }
The above code connects to a MySQL database, queries the table named "users", and prints out the contents of the id and name fields.
Summary: Go language has a wide range of applications in software development, covering network programming, concurrent programming, database operations, etc. Through the above specific code examples, Ximu can help readers better understand and use Go language for software development.
The above is the detailed content of Application fields of Go language in software development. For more information, please follow other related articles on the PHP Chinese website!