R
R
Rodion Yurchenko2018-03-22 15:08:30
go
Rodion Yurchenko, 2018-03-22 15:08:30

How in GOlang to specify in a function that the return type will be either an array or something else?

Good afternoon
For example, there is a function:

func getMsgPack(row string) []byte{
  in := strings.Split(row,"\t")
  if msg_format == "json" {
    b, err := json.Marshal(in)
  }else{
    b, err := msgpack.Marshal(in)
  } // if
  failOnError(err, strings.Join([]string{"Failed to convert msg to msgPack. Format: ", msg_format},""))
  return b
} // func

An error is thrown:
undefined b
undefined err
on these 2 lines:
failOnError(err, strings.Join([]string{"Failed to convert msg to msgPack. Format: ", msg_format},""))
  return b

as I understand it - the problem is in the return type
. That is, either json or msgpack will be returned - how to specify this in the return type?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abroabr, 2018-03-22
@aassdds

Answer to this question:
Go is a statically typed language.
You need to either explicitly convert.
Or use interface{} - but it is not recommended to abuse it.
The answer is based on the source code you attached and the text of the error: But you have a different
problem . You declared variables "b" and "err" inside blocks

if {
} else {
}

Accordingly, these variables are not visible outside the blocks .

E
Evgeniy Ivakha, 2018-03-24
@ivahaev

An error is thrown:
undefined b
undefined err
on these 2 lines:

This is because the variables b and err are not defined. Here's the shading of the variables. To make it work:
var b []byte
  var err error
  if msg_format == "json" {
    b, err = json.Marshal(in)
  } else {
    b, err = msgpack.Marshal(in)
  }

Further, if the return type is the same ([]byte), but the content can be different, you can return one more argument that will contain the type ( json or msgpack )
func getMsgPack(row string) ([]byte, string) {
  // omited
  return b, "json"
}

It is not necessary to specify the type as a string, here for clarity.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question