AdSense

網頁

2022/5/25

Golang 相同欄位的struct轉換 convert structs with identical fields

Golang把一個struct轉成另一個擁有相同欄位的struct。


使用型別轉換T(v)v轉成T

例如下面把Employee轉成相同欄位的Member

main.go

package main

import (
    "fmt"
    "time"
)

type Employee struct {
    ID        int64
    Name      string
    Age       int
    CreatedAt time.Time
}

type Member struct {
    ID        int64
    Name      string
    Age       int
    CreatedAt time.Time
}

func main() {
    emp := Employee{
        ID:        1,
        Name:      "John",
        Age:       33,
        CreatedAt: time.Now(),
    }

    mem := Member(emp)
    fmt.Println(mem) // {1 John 33 2022-05-26 13:25:48.875282 +0800 CST m=+0.000252120}
}

沒有留言:

AdSense