Var Declaration with Type VS Without

var declaration with type vs without

I'm not a Swift developer but I'm fairly certain that it operates in the same way as languages like C# in this regard.

In the first case, the type of the variable is inferred from the type of the expression used to initialise it. Your a variable is thus of type ClassA and can thus refer to any object that is that type or is derived from it. In the second case, you are specifying that the variable is type ClassA explicitly rather than allowing it to be inferred.

In that second case, the annotation is redundant because the specified type is the same as that which would be inferred anyway. If those types were different though, then it would be worthwhile, e.g.

var a: BaseType = DerivedType()

In this case, the variable is being initialised with an object that is one type but the variable is specified to be a type that is more general.

If you are declaring a variable without initialising it then you need an annotation too, because there is no initialising expression from which to infer the variable's type.

difference between declaring variables with var vs without var in go

If you use the :=, the type of the variable is implied from the expression on the right of the sign. If you use =, no assumption is made and you need to specify the type yourself.

In this case, you should write it like this:

var pic [][]uint8 = make([][]uint8, dy)

but this is indeed better because shorter and as clear:

pic := make([][]uint8, dy)

What is the point of using types when declaring a variable in Typescript?

When declaring a variable, if the type of what you're assigning to it can be understood correctly by the TS compiler, then there's no need to define its type. In many cases, declaring an explicit type is not necessary, such as with const num = 5. But sometimes it is necessary, such as when declaring a variable which will be assigned to later, but not now:

let someData: MyData;

Otherwise, someData will be typed as any, which isn't type-safe.

Another example for when it would be useful would be when creating an array which will later be pushed to:

const arr: number[] = [];
// later:
arr.push(5);

The compiler can't infer at arr's declaration what values the array may contain, so number[] should be included when defining arr. (Otherwise, it'll be typed as any[], and any is not type-safe and should be avoided when possible)

Whenever TS can infer the type of a variable correctly and automatically - and most of the time, it can - then feel free to leave off the explicit note of the variable type, since it doesn't help.

Note that declare does something completely different - using that keyword tells TS that a variable with that name is defined in the current scope by other code, such as by a library. Variables which are declared will not exist in emitted code. Unless you have a library or something which defines a variable that Typescript doesn't understand exists, you almost certainly don't want to use declare.

Declaring variables in Go without specifying type

The important part is "will be inferred from the right-hand side" [of the assignment].

You only need to specify a type when declaring but not assigning a variable, or if you want the type to be different than what's inferred. Otherwise, the variable's type will be the same as that of the right-hand side of the assignment.

// s and t are strings
s := "this is a string"
// this form isn't needed inside a function body, but works the same.
var t = "this is another string"

// x is a *big.Int
x := big.NewInt(0)

// e is a nil error interface
// we specify the type, because there's no assignment
var e error

// resp is an *http.Response, and err is an error
resp, err := http.Get("http://example.com")

Outside of a function body at the global scope, you can't use :=, but the same type inference still applies

var s = "this is still a string"

The last case is where you want the variable to have a different type than what's inferred.

// we want x to be an uint64 even though the literal would be 
// inferred as an int
var x uint64 = 3
// though we would do the same with a type conversion
x := uint64(3)

// Taken from the http package, we want the DefaultTransport
// to be a RoundTripper interface that contains a Transport
var DefaultTransport RoundTripper = &Transport{
...
}

Declaring variables without var keyword

No, there's no RAM benefit or anything like that.

What w3schools is talking about is something I call The Horror of Implicit Globals. Consider this function:

function foo() {
var variable1, variable2;

variable1 = 5;
varaible2 = 6;
return variable1 + variable2;
}

Seems simple enough, but it returns NaN, not 11, because of the typo on the varaible2 = 6; line. And it creates a global variable with the typo'd name:

function foo() {
var variable1, variable2;

variable1 = 5;
varaible2 = 6;
return variable1 + variable2;
}
console.log(foo()); // NaN
console.log(varaible2); // 6?!?!?!

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

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

VB.Net variable declaration : type or not to type?

Use a Type!

Really. VB sits on top of .Net, and .Net works best when you stick with explicit types. The only exceptions are with Option Infer turned on (it is now by default) and you also declare variables similar to C#'s var, or if you're doing COM interop or something else that truly requires a dynamic type... and that it is exceedingly rare.

Declare a variable without datatype

A variable must have a type in order to use it. The closest thing to an untyped variable would be the type interface{}, which is an interface type, but has no methods to call.

Since the goal here is to call the NewSession method, declare the variable with an interface containing that method.

var client interface {
NewSession() (*ssh.Session, error)
}
if some_condn {
client = ssh.Dial(params)
} else {
client = my_own_ssh_dial(my_params)
}
session, _ := client.NewSession()


Related Topics



Leave a reply



Submit