Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Golang - 구조체의 slice 필드를 Reflection을 이용해 변경하는 방법

우선, 입문부터 해볼까요? ^^ 간단하게 slice를 만들고 이것에 요소를 추가하는 경우 이런 식으로 코딩할 수 있습니다.

buf := make([]string, 0)
buf := append(buf, "test")

위에서 "append"하는 과정을 Reflection으로 구현한다면 reflect를 이용해 유사한 방식으로 처리하게 됩니다.

value := reflect.ValueOf(&buf)
value := reflect.Append(value.Elem(), reflect.ValueOf("test"))

// 만약 포인터로 전달하지 않으면 reflect.Append 호출에서 예외 발생 - reflect: call of reflect.Value.Elem on slice Value
// value := reflect.ValueOf(buf)

보는 바와 같이, slice가 append를 이용할 때도 그 반환값을 다시 buf 변수에 할당해야만 했던 것처럼, reflect를 이용하는 것도 그와 유사한 것입니다. 바로 이런 점 때문에 결국 buf 변수와 reflect.Append가 반환한 value 변수는 같은 상태를 가리키지 않습니다. 즉, 위와 같은 처리가 원본 변수인 buf에 영향을 주는 것은 아닙니다.

fmt.Printf("%v, %v", len(buf), value)
/* 출력 결과
0, [test]
*/

따라서, reflection으로 처리한 결과를 다시 원본 변수인 buf에 대입하려면 다음과 같은 식의 코딩을 통해 reflect.Value로부터 값을 변환해 줘야 합니다.

buf = value.Interface().([]string)
fmt.Printf("%v, %v\n", len(buf), buf[0]) 
/* 출력 결과
0, test
*/




자, 그럼 타입의 멤버로 slice가 있다면 어떻게 될까요?

type MyType struct {
    Buf []string
}

기본적인 코드는 다음과 같이 시작할 수 있습니다.

t := MyType{}
t.Buf = make([]string, 0)

tValue := reflect.ValueOf(t)

bufValue := tValue.FieldByName("Buf") // 필드 이름으로 조회

bufType := bufValue.Type()
fmt.Printf("%v, %v\n", bufType, bufValue)

fmt.Printf("%v\n", bufType.Elem().Kind())

/* 출력 결과
[]string, []
string
*/

그럼 마찬가지로 slice에 멤버를 추가하는 것도 동일하게 반영할 수 있고,

bufValue = reflect.Append(bufValue, reflect.ValueOf("test"))
fmt.Printf("%v, %v", len(t.Buf), bufValue)
/* 출력 결과
0, [test]
*/

원본에 적용하는 것도 상황이 허락된다면 이렇게 할 수 있습니다.

bufValue = reflect.Append(bufValue, reflect.ValueOf("test"))
t.Buf = bufValue.Interface().([]string)
fmt.Printf("%v, %v", len(t.Buf), t.Buf[0])
/* 출력 결과
1, test
*/

그런데, 여기서 문제가 있습니다. 대개의 경우 reflection을 사용할 때는 대상 인스턴스를 interface {}로 받게 될 것입니다.

t := MyType{}
t.buf = make([]string, 0)

Modify(t)

func Modify(inst interface {}) {
     // ... reflection ...
}

위와 같은 상황에서, slice가 아닌 다른 타입이었다면 reflect.Value의 SetString, SetInt 등을 이용해 값을 설정하는 것이 가능합니다. 그런데, slice 유형이라면 단순히 Set 함수를 이용하는 경우 예외가 발생합니다.

changed := reflect.Append(bufValue, reflect.ValueOf("test"))
bufValue.Set(changed) // 예외 발생:  reflect: reflect.Value.Set using unaddressable value

다행히 예외 메시지에 답이 있는데요, 애당초 구조체 인스턴스를 포인터로 전달했어야 하고, reflection을 하려는 측에서도 Pointer인 경우 reflect.ValueOf/TypeOf를 했던 대상의 원본에 대해 한 번 더 Elem()을 호출해 대상 인스턴스를 가져와야 합니다. 아래의 코드는 그 상황을 보여줍니다.

func main() {
    t := MyType{}
    t.Buf = make([]string, 0)

    Modify(&t);

    /* 또는,
    t := &MyType{}
    t.Buf = make([]string, 0)

    Modify(t);
    */
}

func Modify(t interface{}) {

    tType := reflect.TypeOf(t)
    tValue := reflect.ValueOf(t)

    if tType.Kind() == reflect.Ptr {
        tType = tType.Elem()
        tValue = tValue.Elem()
    }

    bufValue := tValue.FieldByName("Buf")

    bufType := bufValue.Type()
    changed := reflect.Append(bufValue, reflect.ValueOf("test"))

    bufValue.Set(changed)
}




만약 타입의 멤버 이름을 소문자로 바꿔 접근성을 변경하면,

type MyType struct {
    buf []string
}

reflect.Append 코드에서 예외가 발생합니다.

// 예외 발생: reflect: reflect.Copy using value obtained using unexported field
bufValue = reflect.Append(bufValue, reflect.ValueOf("test"))

다른 언어와는 달리, reflection으로도 private 필드에 대한 접근은 할 수 없는 것입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/23/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13011정성태3/21/20226913오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225831오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227477개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226763VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226332.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227441.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226245오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226228디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226392.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20227184.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/20227540.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
13000정성태3/12/20227141.NET Framework: 1176. C# - Oracle.ManagedDataAccess.Core의 성능 카운터 설정 방법
12999정성태3/10/20226645.NET Framework: 1175. Visual Studio - 프로젝트 또는 솔루션의 Clean 작업 시 응용 프로그램에서 생성한 파일을 함께 삭제파일 다운로드1
12998정성태3/10/20226206.NET Framework: 1174. C# - ELEMENT_TYPE_FNPTR 유형의 사용 예
12997정성태3/10/202210659오류 유형: 799. Oracle.ManagedDataAccess - "ORA-01882: timezone region not found" 오류가 발생하는 이유
12996정성태3/9/202215732VS.NET IDE: 175. Visual Studio - 인텔리센스에서 오버로드 메서드를 키보드로 선택하는 방법
12995정성태3/8/20228104.NET Framework: 1173. .NET에서 Producer/Consumer를 구현한 BlockingCollection<T>
12994정성태3/8/20227353오류 유형: 798. WinDbg - Failed to load data access module, 0x80004002
12993정성태3/4/20227168.NET Framework: 1172. .NET에서 Producer/Consumer를 구현하는 기초 인터페이스 - IProducerConsumerCollection<T>
12992정성태3/3/20228637.NET Framework: 1171. C# - BouncyCastle을 사용한 암호화/복호화 예제파일 다운로드1
12991정성태3/2/20227784.NET Framework: 1170. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcode_aac.c 예제 포팅
12990정성태3/2/20227472오류 유형: 797. msbuild - The BaseOutputPath/OutputPath property is not set for project '[...].vcxproj'
12989정성태3/2/20226960오류 유형: 796. mstest.exe - System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.Tips.WebLoadTest.Tip
12988정성태3/2/20225934오류 유형: 795. CI 환경에서 Docker build 시 csproj의 Link 파일에 대한 빌드 오류
12987정성태3/1/20227440.NET Framework: 1169. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 demuxing_decoding.c 예제 포팅
12986정성태2/28/20228254.NET Framework: 1168. C# -IIncrementalGenerator를 적용한 Version 2 Source Generator 실습 [1]
... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...