본문 바로가기
개발/나머지

golang generic을 이용한 여러 타입 슬라이스로부터 구조체 슬라이스 생성하기

by 앗가 2022. 10. 10.
728x90
반응형

같은 크기, 다른 데이터 타입의 슬라이스가 여럿 존재할 때 interface와 tamplate를 이용하여 해당 슬라이스의 원소를 구조체 멤버로 포함하는 구조체를 만들 수 있습니다. 

 

callback함수에서 스프레드 연산자로 입력을 받아 구조체를 리턴하도록 하고 템플릿 슬라이스를 리턴하는 함수를 만들어 callback을 입력 파라미터로 선언해서 구현할 수 있습니다. 

package main

import "fmt"

type TmpType struct {
	Integer   int
	String    string
	SubStruct SubType
}

type SubType struct {
	String1 string
	String2 string
}

func main() {
	a := ConvertValueToInterface([]int{1, 2, 3, 4, 5})
	b := ConvertValueToInterface([]string{"a", "b", "c", "d", "e"})
	c := ConvertValueToInterface([]SubType{{"1", "1"}, {"1", "1"}, {"3", "3"}, {"1", "1"}, {"2", "2"}})

	callback := func(input ...interface{}) TmpType {
		ans := TmpType{
			Integer:   input[0].(int),
			String:    input[1].(string),
			SubStruct: input[2].(SubType),
		}

		return ans
	}

	k := callback(a[1], b[1], c[1])
	fmt.Println(k) // {2 b {1 1}}

	ans := CreateIterTemplate(callback, a, b, c)
	fmt.Println(ans) // [{1 a {1 1}} {2 b {1 1}} {3 c {3 3}} {4 d {1 1}} {5 e {2 2}}]
}

func CreateIterTemplate[T any](callback func(...interface{}) T, iters ...[]interface{}) []T {
	result := make([]T, 0)

	// 슬라이스의 길이를 순환
	for i := 0; i < len(iters[0]); i++ {
		collection := []interface{}{} // callback 입력 생성

		// 어떤 슬라이스에 대하여
		for _, iter := range iters {
			collection = append(collection, iter[i]) // collection에 iter의 i번째 요소 추가
		}

		// callback에서 결과를 받아 result로 저장
		result = append(result, callback(collection...))
	}
	return result
}

func ConvertValueToInterface[T any](someSlice []T) []interface{} {
	ans := make([]interface{}, len(someSlice))
	for i, j := range someSlice {
		ans[i] = j
	}
	return ans
}

 

728x90

'개발 > 나머지' 카테고리의 다른 글

linuxbrew 자동 설치 스크립트  (0) 2023.05.10
golang http request template  (0) 2022.10.09

댓글