Different variable type declaration in Golang - variables

Hi I'm just learning Go since the last view days, read some docs and noted that its something about defining struct or interface. Still cant get the difference between
var result []Struct
and
result := Struct{}
Is there particular docs I can refer to?

The result in the first example is a nil slice. The spec says that variables are initialized to their zero values and that zero value of a slice is nil.
The result in the second example is a Struct value. It uses a short variable declaration and composite literal value for a Struct. The second example identical to
var result Struct
Perhaps you meant to write
result := []Struct{}
for the second example. This is a non-nil zero length slice. The expression []Struct{} is a composite literal for an empty slice of Struct.

Related

Deserializing tuples with argument in Rust

I am a beginner in rust and working with some api that returns bytes that I can deserialize by defining their types.
result: (f64, f64, f64) = api.call();
Can I do the same by dynamically by passing a value n for the number of elements?
All elements of the tuple are of the same type. I would like to do something like this:
result: tuple(f64, 3) = api.call();
Here is the API of the call function.
Edit:
In case anyone ever encounters that issue in the future. I could deserialize the output by adopting this solution.
For reference: call() returns a Result<D: Detokenize, _>. Detokenize is mainly implemented for all T that implement Tokenizable.
All types that can receive the result are listed here.
Note that additional to tuples of various size, it's also implemented for:
impl<T: TokenizableItem + Clone, const N: usize> Tokenizable for [T; N]
Further, note that it is an async function with a Result, meaning you have to await it and deal with the potential error.
So you should(tm) be able to write:
result: [f64; 3] = api.call().await.unwrap();
Of course in a real project I would advise to replace unwrap() with some proper error handling.
Disclaimer: I don't know how to use the rest of ethers-core, so I'm unable to verify this in a test project. This information is purely derived from the documentation.
Static vs dynamic size
[f64; 3] requires you to know the number of elements at compile time.
Note that another Tokenizable is Vec<T>, meaning you could also specify Vec<T> as a result type. The length of this one will then be resolved at runtime, depending on how many elements of T the api.call() returns.
Further background information
Note that there is no such thing as a tuple that has N number of T elements, because a tuple is not a repetition of one type, it's a collection of types. Every element of a tuple can have a different type.
If you want to represent a repetition of one type, an array is what you really want. It's defined as one type T repeated N times: [T; N].

Could someone, please, explain me the implementation of the following "Kotlin Literal high order function"?

I am a newbie in Kotlin, I just started to learn it,
I get the following code example about literal/high order function:
fun myHigherOrderFun(functionArg: (Int)->String) = functionArg(5)
println ( myHigherOrderFun { "The Number is $it" })
prints "The Number is 5"
Which I have difficulty to understand: the function myHigherOrderFun get a lambda function as parameter but i can't understand, where is the (Int) input parameter? I see is passed in functionArg(5)... but i can't realize how is possible that?
Thanks in advance.
To start from the beginning, in Kotlin functions are first-class types, just like numbers and Strings and stuff.  So a function can take another function as a parameter, and/or return a function as its result.  A function which does this is called a ‘higher-order function’.
And that's what you have in your example!  The line:
fun myHigherOrderFun(functionArg: (Int)->String) = functionArg(5)
defines myHigherOrderFun() as a function which takes one parameter, which is itself a function taking a single Int parameter and returning a String.  (myHigherOrderFun() doesn't specify an explicit return type, so it's inferred to be a String too.)
The next line is probably where things are less clear:
println(myHigherOrderFun{ "The Number is $it" })
The first non-obvious thing is that it's calling myHigherOrderFun() with a parameter.  Because that parameter is a lambda, Kotlin lets you omit the usual (…), and use only the braces.
The other non-obvious thing is the lambda itself: { "The Number is $it" }. This is a literal function taking one parameter (of unspecified type).
Normally, you'd have to specify any parameters explicitly, e.g.: { a: Char, b: Int -> /* … */ }.  But if there's exactly one parameter, and you aren't specifying its type, then you can skip that and just refer to the parameter as it.  That's what's happening here.
(If the lambda didn't reference it, then it would be a function taking no parameters at all.)
And because the lambda is being passed to something expecting a function taking an Int parameter, Kotlin knows that it must be an Int, which is why we can get away without specifying that.
So, Kotlin passes that lambda to the myHigherOrderFun(), which executes the lambda, passing 5 as it.  That interpolates it into a string, which it returns as the argument to println().
Many lambdas take a single parameter, so it gets used quite a lot in Kotlin; it's more concise (and usually more readable) than the alternative.  See the docs for more info.

Why there are two ways of declaring variables in Go, what's the difference and which to use?

According to the Go reference there are two ways of declaring a variable
Variable_declarations (in the format of var count = 0 or var count int)
and
Short_variable_declarations (in the format of count := 0)
I found it's very confusing to decide which one to use.
The differences I know (till now) are that:
I can only using a count := 0 format when in the scope of a function.
count := 0 can be redeclared in a multi-variable short declaration.
But they do behave the same as far as I know. And in the reference it also says:
It (the count:=0way) is shorthand for a regular variable declaration with initializer expressions but no types
My confusions are:
If one is just the shorthand way of the other, why do they behave differently?
In what concern does the author of Go make two ways of declaring a variable (why are they not merged into one way)? Just to confuse us?
Is there any other aspect that I should keep my eyes open on when using them, in case I fall into a pit?
The Variable declarations make it clear that variables are declared. The var keyword is required, it is short and expresses what is done (at the file level everything excluding comments has to start with a keyword, e.g. package, import, const, type, var, func). Like any other block, variable declarations can be grouped like this:
var (
count int
sum float64
)
You can't do that with Short variable declarations. Also you can use Variable declarations without specifying the initial value in which case each variable will have the zero value of its type. The Short variable declaration does not allow this, you have to specify the initial value.
One of Go's guiding design principle was to make the syntax clean. Many statements require or it is handy that they allow declaring local variables which will be only available in the body of the statement such as for, if, switch etc. To make the syntax cleaner and shorter, Short variable declaration is justified in these cases and it is unambigous what they do.
for idx, value := range array {
// Do something with index and value
}
if num := runtime.NumCPU(); num > 1 {
fmt.Println("Multicore CPU, cores:", num)
}
Another difference: Redeclaration
Quoting from the Language specification:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. As a consequence, redeclaration can only appear in a multi-variable short declaration. Redeclaration does not introduce a new variable; it just assigns a new value to the original.
This one is also handy. Suppose you want to do proper error handling, you can reuse an err variable because most likely you only need it to check if there were any errors during the last function call:
var name = "myfile.txt"
fi, err := os.Stat(name) // fi and err both first declared
if err != nil {
log.Fatal(err)
}
fmt.Println(name, fi.Size(), "bytes")
data, err := ioutil.ReadFile(name) // data is new but err already exists
// so just a new value is assigned to err
if err != nil {
log.Fatal(err)
}
// Do something with data

Why is named association required for a one-element record aggregate?

When an aggregate contains only one element, as below, positional notation results in a compilation error and we have to use named notation only. Why?
type singleton is record
v : integer;
end record;
v1 : singleton := (0);
results in the compiler message
check.adb:6:23: positional aggregate cannot have one component
check.adb:6:23: write instead "V => ..."
gnatmake: “check.adb" compilation error
whereas this is OK:
v2 : singleton := (v => 0);
Parentheses round an expression are redundant, so (0) = 0 and it's an integer not an array aggregate.
So, for the special case of a one-element aggregate, named association is required to distinguish an aggregate from a simple value.
Contrast this with (0,0) which can only be an aggregate; therefore there is no ambiguity.
Even though in the context of the question, it's obvious to a human programmer which is intended, that will not always be the case.
Consider a one-element aggregate in a multi-dimensional array which is one field of a record; there can be ambiguities that the compiler cannot resolve (at least, before reading a whole lot more of the source file!) and would make life pretty difficult for anyone reading the program.
You don't have to use named notation.
v1 : singleton := (others => 0);
This will assign 0 to all elements in v1 and the compiler will know that is not a number but an array instead.
If the record happen to have different types you could use
v1 : singleton := (others => <>);

Check/display the declared type of an entity (variable, expression...)

I am investigating types in VB especially in VBA. Generally, given an entity there are two types: Effective value type, I guess, is defined as value types in this part of the specification; Declared Type is defined in this part of the specification.
To do tests, I need to use some functions to check types. There are TypeName and VarType. I think they are used to check effective value type of an entity, because TypeName can return DBNull, Decimal and Nothing; VarType can return vbNull, vbEmpty, vbError and vbDecimal. These types exist in the table of effective value types, but not in the table of declared type.
So now, my question is, does anyone know how to check/display the declared type of an entity (variable, expression...)?
Edit 1: Probably for a variable, its declared type is just the type that the declaration of the variable specifies. I would like to insist that, it seems that VBA has declared type for expressions. For instance, Operator Declared Type is mentioned in this link. I think that refers to the declared type of the result of an operation. That means such entities as -i, i+5, i>6... can have a declared type. I would like to know how to display their declared type.
If,
Dim i as integer
i = 6/3
then you do, TypeName(i>3)
it returns Boolean which is the expression's Type based on the Type of the resulting value it holds not operand's declare type. And it complies with the specification given in your link for msdn 2.2 Entities and Declared Types.
Or else are you looking for a syntax/function (e.g. DType, imaginative function) that could return DType(i>3) as integer which is operand's (i) Type? Or rather it's more useful when you have multiple variables within some expression, so you can find all their Types in one go?
e.g. some String that combined all sorts of different TYPE variables in one expressoin.
Just trying to understand when and how this can be useful to you and what could be the end result you are looking for.. Seems like this is more to lanague root definitions.
PS: I do not have reps points to comment. So I added as an answer.