func CreateUsers(ctx context.Context, client *ent.Client, users []struct{ Name string; Age int }) ([]*ent.User, error) { var createdUsers []*ent.User for _, user := range users { u, err := client.User. Create(). SetName(user.Name). SetAge(user.Age). Save(ctx) if err != nil { return nil, fmt.Errorf("failed creating user: %v", err) } log.Printf("user %s was created", user.Name) createdUsers = append(createdUsers, u) } return createdUsers, nil这样写 functionmain里怎么调用
时间: 2024-02-14 10:18:11 浏览: 60
test-func-name-inference.rar_Code Name
你可以编写一个 `main` 函数来调用 `CreateUsers` 函数,例如:
```
package main
import (
"context"
"fmt"
"log"
"ent-example/ent"
)
func main() {
client, err := ent.Open("sqlite3", "file:ent?cache=shared&_fk=1")
if err != nil {
log.Fatalf("failed connecting to database: %v", err)
}
defer client.Close()
// Create some users
users := []struct {
Name string
Age int
}{
{"Alice", 25},
{"Bob", 30},
{"Charlie", 35},
}
createdUsers, err := CreateUsers(context.Background(), client, users)
if err != nil {
log.Fatalf("failed creating users: %v", err)
}
// Print the created users
for _, u := range createdUsers {
fmt.Printf("User %q (age %d) was created with ID %d\n", u.Name, u.Age, u.ID)
}
}
```
在上述代码中,我们先打开了一个 SQLite 数据库连接,并通过 `CreateUsers` 函数创建了一些用户。然后,我们遍历 `createdUsers` 切片,并打印每个用户的信息。
注意,你需要根据你的实际情况修改代码中的数据库连接字符串和 `CreateUsers` 函数的参数。
阅读全文