drll85318 2012-04-05 16:29 采纳率: 100%
浏览 38
已采纳

切片类型的初始化方法无法初始化

I try to implement an initialization method for my own type. However after calling the method the variable is unchanged in main(). I probably haven't fully understood how slices work, here is my example code

package main
import "fmt"

type test [][]float64

func (p *test) init(m, n int){
    tmp := *p
    tmp = make(test, m)
    for i := 0; i < m; i++ {
        tmp[i] = make([]float64, n)
    }
}

func main(){
    var t test
    t.init(10,2)
    fmt.Println(t)
}

I was under the impression that the content of the receiver type * can be changed, but this doesn't seem to be the case for slices. So how do I properly bind my initialization function to my type? I am pretty sure that there is an misunderstanding on my side.... I tried several things like

var t *test = new(test)

or

func (p *test) init(m, n int){
    tmp := *p
    tmp = append(tmp, make(test, m)...)
    for i := 0; i < m; i++ {
        tmp[i] = append(tmp[i], make([]float64, n)...)
    }
}

and so on but all failed..

The only working solution I currently know of is a unbound method which returns the pointer to a fresh slice. This will do for now, but I want to make this a prerequisite in an interface. So how can I bind it?

  • 写回答

1条回答 默认 最新

  • doujing1858 2012-04-05 16:51
    关注
    func (p *test) init(m, n int){
        tmp = make(test, m)
        for i := 0; i < m; i++ {
            tmp[i] = make([]float64, n)
        }
        *p = tmp
    }
    

    You were close. The above does what you want. But there's no reason to avoid a function that returns a fresh slice. That's idiomatic and feels much like writing a constructor in other languages:

    func newTest(m, n int) test {
        t = make(test, m)
        for i := range t {
            t[i] = make([]float64, n)
        }
        return t
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示