我想了解这段代码中的模式和逻辑。

huangapple go评论64阅读模式
英文:

I want to know the pattern and logic in this code

问题

这段代码是一个使用Go语言编写的简单的汽车管理系统。它包含了三个主要的部分:模型(model)、控制器(controller)和服务(service)。

首先,在模型文件夹中有一个名为car.go的文件,定义了一个名为Car的结构体。该结构体包含了汽车的各种属性,如Id、Model、Brand和CreatedAt。

接下来,在控制器文件夹中有一个名为cars.go的文件,定义了一个名为CarController的结构体。该结构体包含了一个指向CarService的指针。CarController结构体中定义了两个方法:New()和GetIndex()。New()方法用于创建一个新的CarController实例,并初始化其carService属性。GetIndex()方法用于获取所有汽车的列表,并将其以JSON格式返回给客户端。

最后,在服务文件夹中有一个名为carService.go的文件,定义了一个名为CarService的结构体。该结构体包含了与数据库相关的属性,如dbName、uri和collectionName。CarService结构体中定义了两个方法:New()和Find()。New()方法用于创建一个新的CarService实例,并从配置文件中获取数据库相关的配置信息。Find()方法用于根据给定的查询条件从数据库中获取汽车列表。

在代码中,*表示指针类型。指针是一种特殊的数据类型,它存储了一个变量的内存地址。通过使用指针,可以在函数之间共享和修改变量的值,而不需要进行复制。在这段代码中,使用指针类型的目的是为了在不同的函数之间传递和修改CarController和CarService的实例。

英文:

i am new to Go so i need to know the pattern and understand the logic in this code

first :
in the car model folder lying a .go file name car.go but its struct was

and in controller folder there a cars.go file as following

type Car struct {
	Id        bson.ObjectId `bson:"_id"`
	Model     string        `bson:"model" form:"" json:"model" binding:"required"`
	Brand     string        `bson:"brand" form:"brand" json:"brand" binding:"required"`
	CreatedAt bson.MongoTimestamp
}

type CarController struct {
	carService *services.CarService
}

func (controller CarController) New() *CarController {
	controller.carService = services.CarService{}.New()

	return &controller
}

func (controller CarController) GetIndex(c *gin.Context) {
	carList := controller.carService.Find(&bson.M{})
	c.JSON(http.StatusOK, &carList)
	//fmt.Println(carList) }
}

and in service folder was a carService.go file as following

type CarService struct {
	dbName         string
	uri            string
	collectionName string
}

func (r CarService) New() *CarService {
	configManger := viperconfing.Config{}
	r.uri = configManger.GetConfig("dbUri")
	r.dbName = configManger.GetConfig("dbName")
	r.collectionName = "car"
	return &r
}

func (r CarService) Find(query *bson.M) (cars []models.Car) {
	session, _ := mgo.Dial(r.uri)
	defer session.Close()
	session.SetSafe(&mgo.Safe{})
	collection := session.DB(r.dbName).C(r.collectionName)

	collection.Find(query).All(&cars)

	fmt.Println(cars)
	return cars
}

I want to know the pattern used in this code i to understand the full logic and what is * meaning ??

答案1

得分: 2

* 是一个指针。

请停止你正在做的一切,然后参加 Go tour

英文:

* is a pointer.

Please stop everything that you are doing and take the Go tour.

huangapple
  • 本文由 发表于 2016年2月8日 03:15:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/35257888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定