syntax question for object initialization [duplicate] - go

This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 2 years ago.
I have the following working code
serverFile, _ := os.OpenFile("server.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
debugFile, _ := os.OpenFile("debug.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
Logger = &BufferedLogger{
ServerWriter: serverFile,
DebugWriter: debugFile,
BufferSize: 100,
}
which I like to simplify, if possible. I tried
Logger = &BufferedLogger{
ServerWriter, _: os.OpenFile("server.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644),
DebugWriter, _: os.OpenFile("debug.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644),
BufferSize: 100,
}
That is wrong syntax. Can someone give me a hint to fix it, or is that impossible?

No, you can't do it all in one statement. And there's a reason for that: you should be handling the error, not ignoring it. Any function that might cause an error will have a multi-valued return, so that you can't use it as an argument to another function, or in an initializer — only in a multi-valued assignment, where you can capture and check the error.

Related

What does "i.(string)" actually mean in golang syntax? [duplicate]

This question already has answers here:
Is this casting in golang?
(1 answer)
What is the meaning of "dot parenthesis" syntax? [duplicate]
(1 answer)
Closed 4 years ago.
I recently started looking for functional go examples and I found this function:
mapper := func (i interface{}) interface{} {
return strings.ToUpper(i.(string))
}
Map(mapper, New(“milu”, “rantanplan”))
//[“MILU”, “RANTANPLAN”]
Now in this function, as you can see the return value of mapper is:
strings.ToUpper(i.(string)).
But, what does this i.(string) syntax mean? I tried searching, but didn't find anything particularly useful.
i.(string) casts (or attempts at least) i (type interface{}) to type string. I say attempts because say i is an int instead, this will panic. If that doesn't sound great to you, then you could change the syntax to
x, ok := i.(string)
In this case if i is not a string, then ok will be false and the code won't panic.
i.(string) means converting i(interface{} type) to string type.

Get single result from multiple-context function call without intermediary variable [duplicate]

This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 6 years ago.
In Go I can use the underscore to ignore a return value from a function that returns multiple values. For instance:
res, _ := strconv.Atoi("64")
Suppose I wanted to use the first value directly into another function call (while ignoring error checking best practices, in this example):
myArray := make([]int, strconv.Atoi("64"))
The compiler will complain that I'm using a multiple-value function in a singe-value context:
./array-test.go:11: multiple-value strconv.Atoi() in single-value context
Is it possible to "pick and choose" from the return values in a single-line without resorting to auxiliary functions?
The only real way to do it is to create some utility "bypass" function, and since this is Go, you'll have to declare one per type.
for example:
func noerrInt(i int, e err) int {
return i
}
then you can do:
myArray := make([]int, noerrInt(strconv.Atoi("64")))
But really, this pretty much sucks, AND ignores best practices.

Is there a way to ignore an error return value in Golang? [duplicate]

This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 6 years ago.
I'm trying to initialize a struct in Go, one of my values is being which returns both an int and an error if one was encountered converted from a string using strconv.Atoi("val").
My question is : Is there a way to ignore an error return value in Golang?
ts := &student{
name: td[0],
ssn: td[2],
next: students.next,
age: strconv.Atoi(td[1]),
}
which gives the error
multiple-value strconv.Atoi() in single-value context
if I add in the err, which i don't want to include in my struct, I will get an error that I am using a method that is not defined in the struct.
You can ignore a return value using _ on the left hand side of assignment however, I don't think there is any way to do it while using the 'composite literal' initialization style you have in your example.
IE I can do returnValue1, _ := SomeFuncThatReturnsAresultAndAnError() but if you tried that in your example like;
ts := &student{
name: td[0],
ssn: td[2],
next: students.next,
age, _: strconv.Atoi(td[1]),
}
It will also generate a compiler error.

what does empty function name in go lang mean? [duplicate]

This question already has answers here:
What is this "err.(*exec.ExitError)" thing in Go code? [duplicate]
(2 answers)
Closed 7 years ago.
I am reading this code and I don't quite understand what line #2 does:
resp := route.Handler(req)
_, nilresponse := resp.(NilResponse)
if !nilresponse {
type NilResponse struct {
}
Thank you
This isn't an empty function name. This is a type-assertion. It is testing that resp is a NilResponse. If it is, then nilResponse will be true, otherwise it will be false. This code throws away the resulting type-asserted value by using _.
See Type Assertions.
If line two is _, nilresponse := resp.(NilResponse) then it's not a function call at all. It's a type assertion. The code is saying "the interface value represented by resp is of type NilResponse.
EDIT; your assignment is kind of odd though because the first return value would be the NilResponse object and the second (if specified) is a flag to indicate whether or not it worked (or maybe an error, can't remember if it's a bool or error). So typically it would be something like; nilResponse, ok := or nilResponse, err :=

What is this "err.(*exec.ExitError)" thing in Go code? [duplicate]

This question already has answers here:
What exactly does .(data_type) method called/do?
(2 answers)
What is the meaning of "dot parenthesis" syntax? [duplicate]
(1 answer)
What is err.(*os.PathError) in Go?
(2 answers)
Explain Type Assertions in Go
(3 answers)
Closed 10 months ago.
For instance, in this answer:
https://stackoverflow.com/a/10385867/20654
...
if exiterr, ok := err.(*exec.ExitError); ok {
...
What is that err.(*exec.ExitError) called? How does it work?
It's type assertion. I can't explain it better than the spec.
It's a type assertion. That if statement is checking if err is also a *exec.ExitError. The ok let's you know whether it was or wasn't. Finally, exiterr is err, but "converted" to *exec.ExitError. This only works with interface types.
You can also omit the ok if you're 100000 percent sure of the underlying type. But, if you omit ok and it turns out you were wrong, then you'll get a panic.
// find out at runtime if this is true by checking second value
exitErr, isExitError := err.(*exec.ExitError)
// will panic if err is not *exec.ExitError
exitErr := err.(*exec.ExitError)
The ok isn't part of the syntax, by the way. It's just a boolean and you can name it whatever you want.

Resources