Skip to content

Instantly share code, notes, and snippets.

@ParkDongJo
Created October 21, 2018 15:23
Show Gist options
  • Save ParkDongJo/f5dff65daccb0bec6d7db818d5b8517c to your computer and use it in GitHub Desktop.
Save ParkDongJo/f5dff65daccb0bec6d7db818d5b8517c to your computer and use it in GitHub Desktop.
값 vs 포인터 리시버(receiver)
package main
import "fmt"
func Append(slice, data []byte) []byte {
l := len(slice)
if l+len(data) > cap(slice) { // 재할당 여부 체크
// 두배의 크기로 할당
newSlice := make([]byte, (l+len(data))*2)
// 내장함수 copy를 사용해 복사
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : l+len(data)]
copy(slice[l:], data)
return slice
}
// 메소드의 시그니처
// func (r ReceiverType) methodName(p ParamType)
// func (r *ReceiverType) methodName(p ParamType)
type ByteSlice []byte
// 리시버를 값으로 받는 경우
func (v ByteSlice) AppendV(data []byte) []byte {
v = Append(ByteSlice(v), data)
return v
}
// 리시버를 포인터로 받는 경우
func (p *ByteSlice) AppendP(data []byte) {
*p = Append(*p, data)
}
// ByteSlice를 좀 더 범용으로 쓸 수 있게 하려면 표준 io.Writer의 인터페이스를 만족시키면 된다.
func (p *ByteSlice) Write(data []byte) (n int, err error) {
*p = Append(*p, data)
return len(data), nil
}
func main() {
greeting := []byte("Hello ")
// 함수를 사용해 처리
fmt.Println("함수:\t\t\t", string(Append(greeting, []byte("World"))))
// 리시버가 값인 메서드를 사용하는 경우
bGreeting := ByteSlice(greeting)
fmt.Println("리시버가 값인 메서드:\t", string(bGreeting.AppendV([]byte("Value"))))
fmt.Println("bGreeting after:\t", string(bGreeting))
// 리시버가 포인터인 메서드
bGreeting.AppendP([]byte("Pointer"))
fmt.Println("리시버가 포인터인 메서드:\t", string(bGreeting))
fmt.Println("bGreeting after:\t", string(bGreeting))
var b ByteSlice
fmt.Fprintf(&b, "Hello, %s", "World")
fmt.Println("[", string(b), "]\n")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment