0

I have studied this post, but I cannot figure out how to use it in my case.

1st package

I have a 1st package with this type:

type Vertex struct {
    X, Y, Z float32
}

There is a slice like:

var V []Vertex

2nd package

There is a 2nd package whose API cannot be modified. In 2nd package, there is this function:

func Compute(points []struct{X, Y, Z float32}) (err error) {
    // ...
    return
}

Call 2nd package by 1st package

Inside 1st package I intend to call the 2nd package. Without a loop that will copy all the fields from the source to the target:

err = secondpackage.Compute(V)

But I receive this error:

Cannot use 'V' (type []Vertex) as type []struct {...}

Didn't work

Inspired by this post, I tried to convert by:

points := []struct {
    X, Y, Z float32
}(V)
err = secondpackage.Compute(points)

But I'm receiving this error:

Cannot convert expression of type '[]Vertex' to type '[]struct { X, Y, Z float32 }'

Megidd
  • 7,089
  • 6
  • 65
  • 142
  • 2
    https://golang.org/doc/faq#convert_slice_with_same_underlying_type – Volker Jun 29 '20 at 13:58
  • So, what is the fastest approach to covert my slices? – Megidd Jun 29 '20 at 14:00
  • Write a for loop and convert each slice element explicitly. – Peter Jun 29 '20 at 14:19
  • The _fastest_ way is `func convert(vs []Vertex) []struct { X, Y, Z float32 }{ return nil }` but that might not be the most correct one. Actually there is just _one_ way: Write a loop. – Volker Jun 29 '20 at 14:21
  • [here](https://golang.org/doc/faq#convert_slice_with_same_underlying_type) `... but you can't change the name (and method set) of elements of a composite type ...` I'm curious to know why? Is it due to a philosophy limitation? Is it due to a methodology limitation? – Megidd Jun 29 '20 at 14:46

1 Answers1

0

Notice here that you are attempting to create a slice:

points := []struct {
    X, Y, Z float32
}(V)

But you are not really giving the values the slice should be filled in. For that you should use {V} instead of (V).

Working example:

https://play.golang.org/p/yYaQM-mPPjB

package main

import (
    "fmt"
)

type Vertex struct {
    X, Y, Z float32
}

var V []Vertex

func Compute(points []struct{ X, Y, Z float32 }) (err error) {
    fmt.Printf("%v\n", points)
    return nil
}
func main() {
    v := Vertex{1, 2, 3}
    points := []struct {
        X, Y, Z float32
    }{v}
    Compute(points)
}

Alternatively, you can be more explicit:

points := []struct {
    X, Y, Z float32
}{{v.X, v.Y, v.Z}}
André Santos
  • 380
  • 1
  • 4
  • 12
  • Thanks :) The problem is that I have `V := []tri.Vertex{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}` which is a slice :( – Megidd Jun 29 '20 at 14:13