Skip to main content

Type และ Struct ใน Go

การประกาศ Type ใน Go


การประกาศ Struct ใน Go

struct ใน ภาษา Go คือ ตัวแปรแบบ user-defined ก็คือผู้เขียนเป็นคนกำหนดเอง ซึ่ง struct สามารถรวมตัวแปรหลายๆตัว และหลายประเภทเข้าเข้ามาอยู่รวมกันเป็น type เดียวกันได้ concept ของ struct จะคล้ายกับ class ในภาษาที่เป็น OOP

type <ชื่อ struct> struct {
  // ข้อมูลเกี่ยวกับ struct นั้นๆ
}


Example 1: การประกาศ struct

package main

import "fmt"

// struct declaration
type User struct {
  name string
  age uint
  email string
}

// Create struct type data
func main() {
  var john User = User{
    name: "John",
    age: 20,
    email: "[email protected]",
  }
  fmt.Println(john) // {John 20 [email protected]}
}


Example 2: การประกาศ struct ซึ่งมี function รวมอยู่ด้วย

package main

import "fmt"

// struct declaration
type User struct {
  name  string
  age   uint
  email string

  // struct can also hasสามารถมี function in the fieldรวมอยู่ด้วย
  speak func(string) string
}

func main() {
  var john User = User{
    name:  "John",
    age:   20,
    email: "[email protected]",
    speak: func(str string) string {
      return "User say: " + str
    },
  }
  fmt.Println("Name: ", john.name)		// Name:  John
  fmt.Println("Age: ", john.age)		// Age:  20
  fmt.Println("Email: ", john.email)	// Email:  [email protected]
  fmt.Println(john.speak("Hi"))			// User say: Hi
}