Github Copilot で Go を書く
11482 ワード
はじめに
最近、Github Copilot をよく使用しています.実際、私の最新のプロジェクト redisql は、提案されたコード スニペットを部分的に使用して作成されました.この記事では、さまざまな例を挙げてその力を説明します.
例
簡単な算術演算から始めて、Web サーバーと SQL トランザクションに進みます.
算数
// Write a function that returns the square of the number.
func square(a int) int {
return a * a
}
次に、より高度なものについて説明します.
// Write a function that multiples two two-dimensional arrays together and returns the result.
func multiply(a [][]int, b [][]int) [][]int {
result := make([][]int, len(a))
for i := range result {
result[i] = make([]int, len(a[i]))
for j := range result[i] {
result[i][j] = a[i][j] * b[i][j]
}
}
return result
}
ウェブ
// Write an http server which returns 'hello world' for any request.
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hello world")
})
http.ListenAndServe(":8080", nil)
}
この時点で、ユーザー データを使用して html レンダリングを要求しようとしました.言うまでもなく、副操縦士はそれを押しつぶし、プログラムの実行方法についての指示でコメントさえしました.
// Write an http web server that returns an html header that shows the user's IP address and the time.
// Usage:
// go run examples/web/httpserverwithhtml.go
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, "<html><body><h1>Your IP is %s. The time is %s</h1></body></html>",
r.RemoteAddr, time.Now().Format(time.RFC1123))
}
私はさらに高度なものを要求しようとしました: HTML 入力で送信されたものをすべてエコーする WebSocket サーバーです.悲しいことに、副操縦士はこのタスクを処理できず、不完全なコードを提案しました.時間の経過とともに、より多くのトレーニングを行うことで、これが可能になる可能性があります.
SQL
// Write a program that opens a MySQL server connection and executes a query on a user table and prints the results.
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// Open a connection to the MySQL server
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/test")
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Execute a query
rows, err := db.Query("SELECT * FROM user")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
// Loop through the rows and print the results
for rows.Next() {
var id int
var name string
if err := rows.Scan(&id, &name); err != nil {
log.Fatal(err)
}
fmt.Println(id, name)
}
}
結論
Copilot は非常に役に立ちます.スニペットはその容量の基本的な例にすぎません.私は積極的に go-copilot にもっと投稿しています.
Reference
この問題について(Github Copilot で Go を書く), 我々は、より多くの情報をここで見つけました https://dev.to/tarekali/writing-go-with-github-copilot-2hpjテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol