user12834955
user12834955

Reputation:

How to create method on slice

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?

Upvotes: 3

Views: 2775

Answers (1)

Lucas Katayama
Lucas Katayama

Reputation: 4570

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

Upvotes: 4

Related Questions