ทิปและทริค จากประสบการณ์ที่เคนใช้ภาษา Go

แปลงค่าตัวแปร

[]byte เป็น string

password := "123456"

hashpassword, err := bcrypt.GenerateFromPassword([]byte(password), 10)

newHashPassword := string(hashPassword[:])

fmt.Printf("hash password is %s", newHashPassword)

Interger เป็น string

in := 10

text := strconv.Itoa(in)

fmt.Printf("text is %s", text)

การเรียกใช้ func ของ struct แบบที่มันแยกกันอยู่คนละไฟล์ คนละ package


ตอนนี้ที่เคนเจอมีด้วยกัน 2 วิธี

## File: controllers/page.go
## Package: controllers


func (this *PageController) GetAll() {
  //วิธีที่ 1
  var pageModel models.Page
  data := pageModel.GetAll()

  //วิธีที่ 2
  data := (&models.Page{}).GetAll()
}

models/page.go

## File: models/page.go
## Package: models


type Page struct {
  gorm.Model
}

func (this *Page) GetAll() []*Page {
  var page []*Page
  
  DB.Find(&page)

  return page
}
0 0 votes
Article Rating
0
Would love your thoughts, please comment.x
()
x