Specman e: When colon equal sign ":=" should be used? - syntax

I saw in some Specman e code example the use of := (colon-equal sign), e.g.:
var regs_type := rf_manager.get_exact_subtype_of_instance(graphics_regs);
When and why should we use := ?
Thank you for your help.

The := means declare a variable of the type the expression on the right returns and assign it to that value. Basically, in your example, the function get_exact_subtype_of_instance(...) returns a value of type rf_struct. The regs_type variable will be declared to that type.
This code is equivalent to (but shorter than):
var regs_type : rf_struct = rf_manager.get_exact_subtype_of_instance(graphics_regs);
This syntax is particularly helpful when casting:
var foo := some_struct.as_a(FOO some_struct_type);

Related

How to declare data type ENUM in Yaskawa MotionWorks IEC 3?

I'm trying to add my own enum in MotionWorks.
After creation of new data type the only available types are ARRAY,STRING,STRUCT.
Writing the following code:
TYPE SimulationType:
(
Passing := 0,
Random := 1,
Failing := 2
) INT := 0;
END_TYPE
does not compile.
Yaskawa seem to be complying to ENUM (according to this list) but I can't figure out how to declare it.
Edit:
I can do the following:
TYPE
ResultType:(Pass, Random, Fail);
END_TYPE
But it doesn't seem to create an enum, as I can't access it's value. I can access it like a structure.
Edit 2:
If I declare:
TYPE
ResultType:(Pass, Random, Fail);
END_TYPE
And set variable
ExpectedResultType : ResultType;
Then in the code I try to use:
IF ExpectedResultType = ResultType.Pass THEN
Done := TRUE;
END_IF;
It compiles, but will not run.
Trying to use this code will not compile:
CASE ExpectedResultType OF
ResultType.Pass:
Done := TRUE;
Error := FALSE;
ResultType.Random:
Done := TRUE;
ResultType.Fail:
Error := TRUE;
Done := FALSE;
END_CASE;
Enums in MotionWorks are declared in data types as this example:
TYPE
MyEnum:(Zero,One,Two,Three);
END_TYPE
ENUMs in MotionWorks can't be assigned a value. First enum will always be equal to 0 (zero), second one to 1 (one), and so on.
Then enums can be used in IF .. END_IF statements like this:
I'll call my variable "i". The variable must be declared as INT. Any other type will not work.
In the code use it like this:
IF i = MyEnum#Zero THEN
(* do some work *)
ELSIF i = MyEnum#One THEN
(* do some other work *)
END_IF
ENUMs can't be used in CASE statements in MotionWorks.
This what I have for Schneider which is IEC61131 so it should be the same
TYPE E_HomeLimitSwitch:
(
ePositiveDirectionRisingEdge := 0,
eNegativeDirectionRisingEdge := 1,
ePositiveDirectionFallingEdge := 2,
eNegativeDirectionFallingEdge := 3
);
END_TYPE
I don't think you INT:=0 should be there.
You can only set the default value to one of your local enum members. Not to other values or even a number as you tried.
Try this instead in line 6:
) INT := Passing;
unlike Codesys, Yaskawa's MotionWorksIEC does not fully support enumerations. In ST language enum usage is quite popular in CASE statements but MotionWorksIEC does not support enum use in case statements.
But, you still can define enums as shown below.
TYPE
PackMLState:(Starting,Starting,Aborting,Aborted,Helding,Held,Etc);
END_TYPE
You can use the enum type as;
IF machineState = PackMLState#Starting THEN
;;
END_IF
Comparing Codesys and MotionWorksIEC (Which is basically Phoenix Contact, KW Software Multiprog), there are some differences. For clarification, the lack of enum use in Cases doesn't make Multiprog an inferior IDE.

Why does initializing just one variable in a definition fail, in golang

In calling a library function with the following signature:
func New() (*sql.DB, Sqlmock, error)
like this:
suite.db, suite.mock, err := sqlmock.New() // inside a suite method
I get error
expected identifier on left side of :=
However, when I change to this
var err error
suite.db, suite.mock, err = sqlmock.New()
the error disappears! Why does declaring k < n variables in a := assignment fail?!
:= is not assignment, it is a short variable declaration. Assignment uses e.g. the simple = operator.
As its name says: it is to declare variables. suite.db is not a variable, it is an expression, more specifically a primary expression; a selector to be exact.
The short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
Where IdentifierList is:
IdentifierList = identifier { "," identifier } .
So you must list identifiers. One "exception" to this "declare new variables rule" is the redeclaration:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) 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.
So you are allowed to use existing variables in a short variable declaration if they were declared in the same block, and you also provide new identifiers (not just existing ones–in which case you would have to use assignment instead).
See related: Why there are two ways of declaring variables in Go, what's the difference and which to use?
When you declare err prior and change := to = it works, because the assignment does not require identifiers on the left of the assignment operator, but expressions:
Assignment = ExpressionList assign_op ExpressionList .
And as detailed above, suite.db is an expression, just like existing variables (identifiers).
:= declares a new variable "identifier". This means you are adding a named thing in your program that can be assigned a value. A struct's fields already are named, as in the golang parser knows they exist so using := makes no sense to golang in this case.
Why does declaring k < n variables in a := assignment fail?!
I'm not sure what "k < n" means, but I think you mean "why does having multiple variables on the left side of := fail?". If that's what you mean, that's not true.
x, y, z := func() (int,int,int) {return 1,2,3}()
fmt.Println(x, y, z)
works just fine. The issue is that golang cannot create an "identifier" (aka a newly named variable) for a struct field since that struct field already exists.
EDIT:
I just had a brainwave that you might have mean "why does having only some new identifiers to declare on the left side of := not work?". This also is not true.
x, y := 5, 6
fmt.Println(x, y)
x, y, z := 1, 2, 3
fmt.Println(x, y, z)
The above works just fine as well.

What is the difference between := and = in Go?

I am new to Go programming language.
I noticed something strange in Go: I thought that it used := and substitutes = in Python, but when I use = in Go it is also works.
What is the difference between := and =?
= is assignment. more about assignment in Go: Assignments
The subtle difference between = and := is when = used in variable declarations.
General form of variable declaration in Go is:
var name type = expression
the above declaration creates a variable of a particular type, attaches a name to it, and sets its initial value. Either the type or the = expression can be omitted, but not both.
For example:
var x int = 1
var a int
var b, c, d = 3.14, "stackoverflow", true
:= is called short variable declaration which takes form
name := expression
and the type of name is determined by the type of expression
Note that: := is a declaration, whereas = is an assignment
So, a short variable declaration must declare at least one new variable. which means a short variable declaration doesn't necessarily declare all the variables on its left-hand side, when some of them were already declared in the same lexical block, then := acts like an assignment to those variables
For example:
r := foo() // ok, declare a new variable r
r, m := bar() // ok, declare a new variable m and assign r a new value
r, m := bar2() //compile error: no new variables
Besides, := may appear only inside functions. In some contexts such as the initializers for "if", "for", or "switch" statements, they can be used to declare local temporary variables.
More info:
variable declarations
short variable declarations
= is just assignment
:= is declare-and-initialize construct for new vars (at least one new var) inside the function block (not global):
var u1 uint32 //declare a variable and init with 0
u1 = 32 //assign its value
var u2 uint32 = 32 //declare a variable and assign its value at once
//declare a new variable with defining data type:
u3 := uint32(32) //inside the function block this is equal to: var u3 uint32 = 32
fmt.Println(u1, u2, u3) //32 32 32
//u3 := 20//err: no new variables on left side of :=
u3 = 20
fmt.Println(u1, u2, u3) //32 32 20
u3, str4 := 100, "str" // at least one new var
fmt.Println(u1, u2, u3, str4) //32 32 100 str
:= is the "short declaration form" for declaring and initializing variables. It does type inference on the value that you are assigning to set the variable's type.
If you attempt to assign with the short declaration form to the same variable in the same scope, the compiler will throw an error.
Be on the lookout for the short declaration form "shadowing" the same variable in an enclosing scope (especially with errors)
= requires the var keyword when declaring a variable and the variable's type explicitly following the variable name. You can actually leave the = off the declaration since Go has a initial value for all types (strings are initialized as "", ints are 0, slices are empty slices). It can also be used for reassignment with just a value, ie
var s string = "a string" // declared and initialized to "a string"
s = "something else" // value is reassigned
var n int // declared and initialized to 0
n = 3
Inside a function, the := short assignment statement can be used in place of a var declaration with implicit type.
for example:
package main
import "fmt"
func main() {
var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
fmt.Println(i, j, k, c, python, java)
}
NOTICE: the variable declared with := can only be used inside the function block.
I took time to figure out a mistake I made that could help you to clarify the difference between := and =.
Consider the following code:
type mystruct struct {
a int
arr []int
}
func main() {
m := mystruct{}
m.arr := make([]int, 5) //compilation error because m.arr is already declared.
m.arr = make([]int, 5) //compiles
}
= is used as statically typed.
:= is used as dynamically typed.
example:
var a = 30 # statically typed and is a compile time check
b := 40 # dynamically checked.
Note the difference in := and = in range clauses as well. The following examples are adapted from the spec.
The iteration variables may be declared by the "range" clause using a form of short variable declaration (:=). In this case their types are set to the types of the respective iteration values and their scope is the block of the "for" statement; they are re-used in each iteration. If the iteration variables are declared outside the "for" statement, after execution their values will be those of the last iteration.
= range ...:
i := 2
x = []int{3, 5, 7}
for i, x[i] = range x { // i,x[2] = 0,x[0]
break
}
// now i == 0 and x == []int{3, 5, 3}
var (key string; val interface{})
m := map[string]int{"mon":0, "tue":1, "wed":2, "thu":3, "fri":4, "sat":5, "sun":6}
for key, val = range m {
h(key, val)
}
// key == last map key encountered in iteration (note order of map iteration is random)
// val == map[key]
:= range ...:
var a [10]string
for i, s := range a {
// type of i is int, type of s is string
// s == a[i]
someFunction(i, s)
}
// i and s are no longer accessible here.
for i := range a { // roughly equivalent to `for i := 0; i < len(a); i++`
someFunction(i, a[i])
}
for _, s := range a {
anotherFunc(s)
}
// Above is roughly equivalent to:
{
var s string
for i := 0; i < len(a); i++ {
s = a[i]
anotherFunc(s)
}
}
// s not accessible here
The most verbose way to declare a variable in Go uses the var keyword, an explicit type, and an assignment.
var x int = 10
Go also supports a short declaration format. When you are within a function, you can
use the := operator to replace a var declaration that uses type inference.
var x = 10
x := 10
There is one limitation on :=. If you are declaring a variable at package level, you
must use var because := is not legal outside of functions.
There are some situations within functions where you should avoid :=
When initializing a variable to its zero value, use var x int. This makes it clear
that the zero value is intended.
When assigning an untyped constant or a literal to a variable and the default type
for the constant or literal isn’t the type you want for the variable, use the long var
form with the type specified. While it is legal to use a type conversion to specify
the type of the value and use := to write x := byte(20), it is idiomatic to write
var x byte = 20.
Because := allows you to assign to both new and existing variables, it sometimes
creates new variables when you think you are reusing existing ones. In those situations, explicitly declare all
of your new variables with var to make it clear which variables are new, and then
use the assignment operator (=) to assign values to both new and old variables.
While var and := allow you to declare multiple variables on the same line, only use
this style when assigning multiple values returned from a function or the comma ok
idiom.
Learning Go Jon Bondner

Go fails to infer type in assignment: "non-name on left side of :="

This snippet works as expected play.golang.org/p/VuCl-OKMav
i := 10
next := 11
prev, i := i, next
However this nearly identical snippet gives non-name f.Bar on left side of := play.golang.org/p/J8NNWPugQG
type Foo struct {
Bar int
}
f := Foo{10}
next := 11
prev, f.Bar := f.Bar, next
What's special about the struct that stops type inference? Is this a bug?
It's an open issue.
Issue 6842: spec: Assigning to fields with short declaration notation
It's not really a type inference issue, it's just that the left-hand-side of := must be a list of identifiers, and f.Bar is not an identifier, so it can't be declared — not even with :='s slightly-more-permissive rules for what it can declare. See "Short variable declarations" in The Go Programming Language Specification.
From the spec's Short variable declarations section:
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.
So if you declare the variable inside another type (struct Foo in the example), it is disqualified by "provided they were originally declared earlier in the same block".
So the answer is to just set the pre-declared variable equal not using the := syntax to the value:
...
var prev int
prev, f.Bar = f.Bar, next
...
it is just that you already assigned f to Foo
f := Foo{100}
in this case f.Bar is 100
so to reassign it just remove the column
var prev string
f := Foo{10}
next := 11
prev, f.Bar = f.Bar, next
this will work

What does := mean in Go?

I'm following this tutorial, specifically exercise 8:
http://tour.golang.org/#8
package main
import "fmt"
func swap(x, y string) (string, string) {
return y, x
}
func main() {
a, b := swap("hello", "world")
fmt.Println(a, b)
}
Specifically what does the := mean? Searching for Go documentation is very hard, ironically.
A short variable declaration uses the syntax:
ShortVarDecl = IdentifierList ":=" ExpressionList .
It is a shorthand for a regular variable declaration with initializer expressions but no types:
Keep on going to page 12 of the tour!
A Tour of Go
Short variable declarations
Inside a function, the := short assignment statement can be used in
place of a var declaration with implicit type.
(Outside a function, every construct begins with a keyword and the :=
construct is not available.)
As others have explained already, := is for both declaration, and assignment, whereas = is for assignment only.
For example, var abc int = 20 is the same as abc := 20.
It's useful when you don't want to fill up your code with type or struct declarations.
The := syntax is shorthand for declaring and initializing a variable, example f := "car" is the short form of var f string = "car"
The short variable declaration operator(:=) can only be used for declaring local variables. If you try to declare a global variable using the short declaration operator, you will get an error.
Refer official documentation for more details
:= is not an operator. It is a part of the syntax of the Short variable declarations clause.
more on this: https://golang.org/ref/spec#Short_variable_declarations
According to my book on Go, it is just a short variable declaration statement
exactly the same as
var s = ""
But it is more easy to declare, and the scope of it is less expansive. A := var decleration also can't have a type of interface{}. This is something that you will probably run into years later though
:= represents a variable, we can assign a value to a variable using :=.

Resources