Go getValueFromPath()

Jmnote (토론 | 기여)님의 2025년 3월 11일 (화) 14:11 판 (새 문서: ==개요== ;Go getValueFromPath() <syntaxhighlight lang='go'> package main import ( "fmt" "reflect" "strings" ) type User struct { Name string Profile Profile } type Profi...)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

개요

Go getValueFromPath()
package main

import (
	"fmt"
	"reflect"
	"strings"
)

type User struct {
	Name    string
	Profile Profile
}

type Profile struct {
	Email string
	Phone string
}

func main() {
	user := User{
		Name: "John Doe",
		Profile: Profile{
			Email: "john.doe@example.com",
			Phone: "123-456-7890",
		},
	}

	fmt.Println(getValueFromPath(user, ".X"))             // <nil>
	fmt.Println(getValueFromPath(user, ".Name"))          // "John Doe"
	fmt.Println(getValueFromPath(user, ".Profile"))       // {john.doe@example.com 123-456-7890}
	fmt.Println(getValueFromPath(user, ".Profile.Email")) // "john.doe@example.com"
	fmt.Println(getValueFromPath(user, ".Profile.Phone")) // "123-456-7890"
}

func getValueFromPath(v interface{}, path string) interface{} {
	fields := strings.Split(path[1:], ".")
	rv := reflect.ValueOf(v)
	for _, field := range fields {
		rv = rv.FieldByName(field)
		if !rv.IsValid() {
			return nil
		}
	}
	return rv.Interface()
}
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}