Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create method on slice

Tags:

go

I have this:

type DbTransaction struct {
  Tx *sql.Tx
  DidTransactionFinish bool
}

type DbTransactionSlice []DbTransaction

func (v *DbTransactionSlice) push(x *DbTransaction) *DbTransaction{
  append(v, x)
  return x;
}

I just want a method that appends an element and returns that element. The error I get is:

Cannot use 'v' (type *DbTransactionSlice) as type []Type

anyone know how to do what I want to do?


1 Answers

You can do something like this:

package main
import (
    "fmt"
)

type me []string


func (m *me) Add(a string) {
    *m = append(*m, a)
}

func main() {
    fmt.Println("Hello, playground")
    hello := me{}
    hello.Add("asdasD")
    
    fmt.Println(hello)
    
}

https://play.golang.org/p/D9V8XgH7HWw

like image 78
Lucas Katayama Avatar answered Jun 25 '26 05:06

Lucas Katayama