代码之家  ›  专栏  ›  技术社区  ›  MickeyThreeSheds

函数接受接口时向字符串传递指针?

go
  •  1
  • MickeyThreeSheds  · 技术社区  · 6 年前

    我有以下界面:

    type HeadInterface interface{
        Head(interface{})
    }
    

    然后我有以下功能:

    func Head(slice HeadInterface, result interface{}){
        slice.Head(result)
    }
    
    func (slice StringSlice) Head(result interface{}){
        result = reflect.ValueOf(slice[0])
        fmt.Println(result)
    }
    

    还有。。。这是我从一个调用方法的应用程序中对函数的调用。。。

    func main(){
        test := x.StringSlice{"Phil", "Jessica", "Andrea"}
    
        // empty result string for population within the function
        var result string = ""
    
        // Calling the function (it is a call to 'x.Head' because I lazily just called th import 'x')
        x.Head(test, &result)
    
        // I would have thought I would have gotten "Phil" here, but instead, it is still empty, despite the Println in the function, calling it "phil.
        fmt.Println(result)
    }
    

    1 回复  |  直到 6 年前
        1
  •  0
  •   jecolon    6 年前

    正如你在笔记中所说,我很确定这不必这么复杂,但要在你的环境中发挥作用:

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    type HeadInterface interface {
        Head(interface{})
    }
    
    func Head(slice HeadInterface, result interface{}) {
        slice.Head(result)
    }
    
    type StringSlice []string
    
    func (slice StringSlice) Head(result interface{}) {
        switch result := result.(type) {
        case *string:
            *result = reflect.ValueOf(slice[0]).String()
            fmt.Println("inside Head:", *result)
        default:
            panic("can't handle this type!")
        }
    
    }
    
    func main() {
        test := StringSlice{"Phil", "Jessica", "Andrea"}
    
        // empty result string for population within the function
        var result string = ""
    
        // Calling the function (it is a call to 'x.Head' because I lazily just called th import 'x')
        Head(test, &result)
    
        // I would have thought I would have gotten "Phil" here, but instead, it is still empty, despite the Println in the function, calling it "phil.
        fmt.Println("outside:", result)
    }