Why type assertion that surely fails is not a syntax error? [duplicate] - go

This question already has answers here:
Explain Type Assertions in Go
(3 answers)
Closed 8 months ago.
I was going through this tour of go.
Initially i is declared an interface with type string.
var i interface{} = "hello"
But when we do
f = i.(float64) // panic
My question is, why isn't this caught during compile time in golang.
C++ generics catch this during compile time, unlike go which decides to do it at runtime.
The "type" information for i exists during compilation.
This kind of issue would be something that would make it easier (from a golang programmer's perspective) to catch during compilation than runtime.
edit: Eduardo Thales suggested that generics were included later in golang. I was under the assumption that the underlying mechanism of interfaces is generics. apparently not. Thanks Eduardo

The language specification explicitly says that false type assertions cause a run-time panic. See:
If the type assertion is false, a run-time panic occurs.
Also, there's nothing in the language that says that you can't make a program that will unambiguously panic. For example, this is a valid program that will compile without error:
package main
import "fmt"
func main() {
fmt.Println("Don't panic!")
panic(1)
}

You're mixing up generics and variable types.
Take this as an example:
items := []string{"item1", "item2"}
fmt.Println(slices.Contains(items, "item1"))
The variable type is slice. The generic part is string, which is regarded in slices.Contains.
So, fmt.Println(slices.Contains(items, 1)) would cause a compile time error because the generic type string doesn't match the generic type int.
(NB: slice is not the best representative of a typical generic in Go because usually they look different, but it's the easiest one to grasp the concept.)
#mkopriva has already answered why your code doesn't cause a compile error: float64 is a valid subtype of interface{}.
If it wasn't, you'ld get a compile time error here as well, e.g. as in
var i string = "hello"
f := i.(float64) // compile time error
Generics don't even exist here, though, and neither they did in your example.

Related

In go language, may I define allowed values of a string in a struct and/or force creation only via constructor? Or avoid direct creation of a struct? [duplicate]

This question already has answers here:
Creating a Constant Type and Restricting the Type's Values
(2 answers)
What is an idiomatic way of representing enums in Go?
(14 answers)
Closed 8 months ago.
I have a struct Direction with a value of type string. Direction should be N, S, W or E.
type Direction struct {
value string
}
Inspired by an answer of this question: Does Go have "if x in" construct similar to Python? I guess a good way to create Direction in a valid manner can be this one:
func NewDirection(direction string) Direction {
switch direction {
case "N","S","W","E": return Direction{direction}
}
panic("invalid direction")
}
But this is not enough for me because I can still create invalid Direction:
d := Direction{"X"}
I also found this interesting article about enforcing the use of constructor in go. Reading this article I can see that is necessary the usage of another package. May I have a "protected" struct in, for example, main package?
You've already done almost everything you should do by convention:
make the field unexported
provide a constructor
put a comment on the type stating that the constructor should be used, and explain how zero-values are treated (if that matters)
Now users of the package can't modify the field, and the existence of the constrictor makes it clear that it should be called to create valid instances. This is the convention that is set by the standard library.
Sure, there are other ways that you can make it even harder to invalidate values but this is essentially just wasting time and overcomplicating your code for the sake of an unwinnable arms race against an imaginary opponent.
If someone doesn't understand the language and doesn't read documentation, then they're always going to find a way to misuse it. If they are actively trying to sabotage themselves, there's nothing you can do to stop them and no reason to either.
Packages are the smallest functional unit of code organization in Go. There is no way to protect field at, for example, the file level. Even files within the same package effectively operate as if all their code was in the same file. Therefore, any code in the same package as the constructor will have the same privileges as the constructor.

What's the difference between generic and non-generic use of interfaces? [duplicate]

This question already has answers here:
What are the benefits of replacing an interface argument with a type parameter?
(2 answers)
Closed 8 months ago.
In the new Type Parameters Design Draft, you can now apply an interface constraint to a generic function:
func prettyPrint[T Stringer](s T) string {
...
}
But, this was already possible by using an interface parameter without generics:
func prettyPrint(s Stringer) string {
...
}
What's the difference between using the first and using the second?
I assume the question refers to the latest draft of the Type Parameters proposal, which may end up in Go in 1.18.
The first is parametric polymorphism. The compiler verifies that the constraint is satisfied, and then generates code that takes a statically-known type. Importantly, it's not boxed.
The second is runtime polymorphism. It takes a type that's unknown at compile time (the only thing known is that it implements the interface) and works on a boxed interface pointer.
Performance considerations aside, in this simple case you can use either approach. Generics really help with the more complicated cases where the current tools don't work well.

How do you implement a container for different types in Go? [duplicate]

This question already has answers here:
Any type and implementing generic list in go programming language
(2 answers)
Generic Structs with Go
(1 answer)
Closed 5 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
The following code implements a List of ints in Go:
package main
import "fmt"
type List struct {
Head int
Tail *List
}
func tail(list List) *List {
return list.Tail
}
func main() {
list := List{Head: 1, Tail:
&List{Head: 2, Tail:
&List{Head: 3, Tail:
nil}}}
fmt.Println(tail(list).Head)
}
Problem is this only works for int. If I wanted a list of strings, I'd need to re-implement every list method (such as tail) again! That's obviously not practical, so, this can be solved by using an empty interface:
type List struct {
Head interface{} // Now works for any type!
Tail *List
}
Problem is, 1. this seems to be much slower because of type casts, 2. it throws aways type safety, allowing one to type-check anything:
// This type-checks!
func main() {
list := List{Head: 123456789 , Tail:
&List{Head: "covfefe" , Tail:
&List{Head: nil , Tail:
&List{Head: []int{1,2}, Tail:
nil}}}}
fmt.Println(tail(list).Head)
Obviously that program should not type-check in a statically typed language.
How can I implement a List type which doesn't require me to re-implement all List methods for each contained type, but which keeps the expected type safety and performance?
Go doesn't have generic types, so you're stuck with the options you listed. Sorry.
Meanwhile, Go's built-in maps and slices, plus the ability to use the empty interface to construct containers (with explicit unboxing) mean in many cases it is possible to write code that does what generics would enable, if less smoothly.
If you know more about the elements you want to store in the container, you may use a more specialized interface type (instead of the empty interface interface{}), which
could help you avoid using type assertions (keep good performance)
and still keep type safety
and it can be used for all types that (implicitly) implement your interface (code "re-usability", no need to duplicate for multiple types).
But that's about it. See an example of this here: Why are interfaces needed in Golang?
Also just in case you missed it, the standard library already has a doubly linked list implementation in the container/list package (which also uses interface{} type for the values).
It's important to acknowledge that we expect generic types to be slower, not faster. The excellent fastutil library for Java outperforms the more flexible classes from the standard library by using concrete implementations.
Russ Cox (one of Go's authors) summarises the situation like this:
(The C approach.) Leave them out.
This slows programmers.
(The C++ approach.) Compile-time specialization or macro expansion.
This slows compilation.
(The Java approach.) Box everything implicitly.
This slows execution.
You may be interested in this living document which has a lot of the pros and cons outlined.
As the other answer points out, Go does not support the design you're trying to achieve here. Personally, I'd just duplicate the code - it's not much, the tests are cheap, and most of the time you don't actually need the generic behaviour you want to implement.

Why Does Golang Allow Compilation of Unused Functions?

Private/unexported functions not used could be detected. Why the compiler doesn't complain like it does for unused variables?
Edit: The question also applies to unused private types/interfaces too.
I believe this is a combination of scope and the default interface {}.
This is the same reason that you can declare a variable at the package level that is unused and the code will build just fine.
This snippet is perfectly valid go code:
package main
import (
"fmt"
"time"
)
var (
testVar = "sup"
)
func main() {
start := time.Now()
fmt.Println("This sure was a test")
//Mon Jan 2 15:04:05 -0700 MST 2006
fmt.Println("Finished!\nTimeElapsed:", time.Since(start))
}
Even though the variable testVar is never used.
There are several related questions here, and I think they all have the same general answer.
Why are unused variables not allowed?
Why are unused function parameters allowed if unused variables are not?
Why are unused functions/structs allowed?
...
The general answer is that unused variables in the scope of a function are ALWAYS either a waste of compiler time, or a legitimate error - so they are strictly not allowed.
However, unused function parameters, as well as private structs and functions, may satisfy an interface. At the very least they ALL satisfy the default interface {}. And as such, they are not at all guaranteed to be errors..
There doesn't appear to be any official documentation outlining the reasoning behind this particular corner of the golang philosophy, but as pointed out in the answer to a similar question you might have better luck finding answers and asking questions on the golang-nuts forum.
Hope this helps!

golang cast to relfect.Type [duplicate]

This question already has answers here:
golang type assertion using reflect.Typeof()
(6 answers)
Closed 7 years ago.
My Problem is as follows:
I have a slice of reflect.Value, that was returned from a MethodByName("foo").Call().
now i want to cast the contained values to their types, which i dont know statically, but in form of relflect.Type
Basically what i want to do is:
values[0].Interface().(mytype)
but with reflection
values[0].Interface().(reflect.TypeOf(responseObject))
This gives me the compilation error:
reflect.TypeOf(responseObject) is not a type
Is there a way to do this in go?
Thanks and regards
BillDoor
If you have code using the normal type assertion syntax like:
x := v.(mytype)
Then the compiler knows that the variable x is of type mytype, and generates code accordingly. If the language let you use an expression in place of the type, then the compiler would have no way of knowing what type x is, and consequently no way to generate code that uses that variable.
If you only know the type of value at runtime, then you will need to stick with the reflect.Value API. You can determine the value's type using its Type method, and there are methods that will let you access struct fields, indexes in slices or arrays, etc.
You will only be able to move back to regular syntax when you have a type you know about at compile time.
What is a cast (type assertion)? It has two effects:
At compile time, the compile-time of the whole type assertion expression is the type casted to.
At runtime, a check is made on the actual runtime type of the value, and if it is not the type casted to, it will generate a runtime error.
Obviously, #1 doesn't make sense for a type that is not known at compile-time, because how can the compile-time type of something depend on something not known at compile time?
You can still do manually do #2 for a type that is not known at compile time. Just get the runtime type of the value using reflect.TypeOf() and compare it against the runtime.Type you have.

Resources