How to tell Go compiler to ignore unused variable? [duplicate] - go

This question already has answers here:
Go: Unused variable
(2 answers)
Closed 1 year ago.
I have code that loops through each rune of a string like so:
for i, character := range "abcdefghjklmnopqrstuv" {
fmt.Printf("character and i: ", character, i)
}
However, I have no need do anything with i. I only need that for the loop to work. If I leave i out of fmt.Printf, the compiler complains that I have defined something I did not use. If I leave i in, it clutters my console output.
How can I can tell the compiler to ignore the unused variable?

Use the blank identifier _:
for _, character := range "abcdefghjklmnopqrstuv" {
fmt.Printf("character: ", character)
}
This is covered in the Tour of Go.

I understand the confusion.
Unlike most program languages Go does not allow unused variables. This is because of a design decision to enforce that on this level unlike as a optional choice for each developer as other languages do.
So you can use the blank identifier as another answer mentioned but this is because of the way Go works.

Related

What does ` {…}` mean? [duplicate]

This question already has an answer here:
What is the meaning of "...Type" in Go?
(1 answer)
Closed 2 years ago.
In a lot of go repositories in many places generally, when error responses are generated i see
if error != nil {…}
What does {…} mean here.
In this case '{...}' is not really a Golang syntactic construct but just usage of ellipsis to say "here in this {} block you should do something to handle error". It is just placeholder for subjective code to handle error in a way that makes sense in your use case. People do that in documentation to keep examples not-cluttered by error handling logic but still highlighting proper usage of library including error handling.
For completeness there are other places in Golang where ... actually has a special meaning. Those places are:
As argument to go command ... means recursive package list wildcard. go test ./... will test all golang packages found in directory './' and any level of subdirectories
Array literals arr := [...]string{"foo", "bar"} will substitute ... with number of items in array literal, here it will be 2. If you add "baz" at some point, you don't have to update number in [].
Variadic function arguments func foo(args ...int) - see here.
When passing a slice to a variadic function you can unwrap it by adding ... and each element of the slice will be passed as an additional argument. See sum(nums...) in example linked above.

What does _, mean? [duplicate]

This question already has answers here:
What is "_," (underscore comma) in a Go declaration?
(9 answers)
Closed 7 years ago.
I'm new to Go and came across this line of code while browsing through some other threads:
if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err)
What does the _, after the if mean? Is it specifying that something will be assigned in the if condition (as it appears is happening with err)? I couldn't find an example of this syntax on the wiki and I'm very curious to see what it's used for.
Here's a link to the thread I was looking at if it helps:
How to check if a file exists in Go?
Because os.Stat returns two values, you have to have somewhere to receive those if you want any of them. The _ is a placeholder that essentially means "I don't care about this particular return value." Here, we only care to check the error, but don't need to do anything with the actual FileInfo Stat gives us.
The compiler will just throw that value away.

Assign multi-value to struct literal [duplicate]

This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 7 years ago.
Is there any way in Go to do this:
segment := Segment{
CumulativeDistanceMm: strconv.Atoi(record[9]),
Length: strconv.Atoi(record[1]),
LinkId: strconv.Atoi(record[8]),
SegmentId: strconv.Atoi(record[2]),
}
The error that I get is that strconv.Atoi returns multiple values so I can't assign it directly to the struct properties. If it was a variable I could use the underscore to ignore the second value. Can I do something similar for structs?
strconv.Atoi can fail and you have to deal with this failure. If such failures are absolutely impossible you would write a function func MustAtoi(s string) int which panics on failure and use that one in your struct initialization.
In Go doing some programming instead of using syntactical sugar or fancy syntax is common.
Most probably you should rethink your error handling.

What are common "Go-tchas" that someone learning Golang should watch out for? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
For example, the "Effective Go" documentation has the following entries:
Like C, Go's formal grammar uses semicolons to terminate statements, but unlike in C, those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert semicolons automatically as it scans, so the input text is mostly free of them.
Cut off some parts for brevity.
Write them like this
if i < f() {
g()
}
not like this
if i < f() // wrong!
{ // wrong!
g()
}
The wrong version when executed produces the following error messages:
/tmp/test.go:6: missing condition in if statement
/tmp/test.go:6: true evaluated but not used
IMO, both messages don't give the coder a clue about misplaced curly braces. Had I failed to read the documentation above, I would have probably written some Go code in the future using the wrong version (I usually use the 1st version in writing code that uses curly braces), then banged my head as to why I'm missing an "if" condition when one is clearly present.
Are there other "gotchas" in Golang that I should be aware of?
This could've been just a comment, but posted as an answer to lay more emphasis on it, because I do believe the linked article is really good, useful even for non-starters and it is still unknown.
This is the best and most complete I've seen:
50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs
It has topics ranging from total beginner (like "Opening Brace Can't Be Placed on a Separate Line" or "Unused Imports") to advanced beginner (like "nil" Interfaces and "nil" Interfaces Values or "Preemptive Scheduling").
So a nice summary of the common pitfalls or "gotchas" is basically their table of contents, all of which you can read more about there:
Total Beginner:
Opening Brace Can't Be Placed on a Separate Line
Unused Variables
Unused Imports
Short Variable Declarations Can Be Used Only Inside Functions
Redeclaring Variables Using Short Variable Declarations
Accidental Variable Shadowing
Can't Use "nil" to Initialize a Variable Without an Explicit Type
Using "nil" Slices and Maps
Map Capacity
Strings Can't Be "nil"
Array Function Arguments
Unexpected Values in Slice and Array "range" Clauses
Slices and Arrays Are One-Dimensional
Accessing Non-Existing Map Keys
Strings Are Immutable
Conversions Between Strings and Byte Slices
Strings and Index Operator
Strings Are Not Always UTF8 Text
String Length
Missing Comma In Multi-Line Slice/Array/Map Literals
log.Fatal and log.Panic Do More Than Log
Built-in Data Structure Operations Are Not Synchronized
Iteration Values For Strings in "range" Clauses
Iterating Through a Map Using a "for range" Clause
Fallthrough Behavior in "switch" Statements
Increments and Decrements
Bitwise NOT Operator
Operator Precedence Differences
Unexported Structure Fields Are Not Encoded
App Exits With Active Goroutines
Sending to an Unbuffered Channel Returns As Soon As the Target Receiver Is Ready
Sending to an Closed Channel Causes a Panic
Using "nil" Channels
Methods with Value Receivers Can't Change the Original Value
Intermediate Beginner:
Closing HTTP Response Body
Closing HTTP Connections
Unmarshalling JSON Numbers into Interface Values
Comparing Structs, Arrays, Slices, and Maps
Recovering From a Panic
Updating and Referencing Item Values in Slice, Array, and Map "for range" Clauses
"Hidden" Data in Slices
Slice Data Corruption
"Stale" Slices
Type Declarations and Methods
Breaking Out of "for switch" and "for select" Code Blocks
Iteration Variables and Closures in "for" Statements
Deferred Function Call Argument Evaluation
Deferred Function Call Execution
Failed Type Assertions
Blocked Goroutines and Resource Leaks
Advanced Beginner:
Using Pointer Receiver Methods On Value Instances
Updating Map Value Fields
"nil" Interfaces and "nil" Interfaces Values
Stack and Heap Variables
GOMAXPROCS, Concurrency, and Parallelism
Read and Write Operation Reordering
Preemptive Scheduling

vb6 & character after a variable [duplicate]

This question already has answers here:
What do ! and # mean when attached to numbers in VB6?
(3 answers)
Closed 9 years ago.
There is the following in some code I'm trying to figure out:
For I& = 1 To...
I'm not familiar with the & after a variable. What does that represent?
After some further research, it looks like the I& is being defined as a type LONG. Now my questions is why would they be doing this? Is it overkill or just legacy code?
The legacy BASIC Language had several ways of declaring variables. You could use data type suffixes ($, %, &, !, or #) to the variable name
x$ = "This is a string" ' $ defines a string
y% = 10 ' % defines an integer
y& = 150 ' & defines a long integer
y! = 3.14 ' ! defines a single
y# = 12.24 ' # defines a double
Legacy. Old-school (pre-.NET) Visual Basic used variable name suffixes in lieu of (optionally) variable types.
You are right - putting an ampersand & after a number or a variable means that it is of a Long 32-bits type.
So the answer is, how many iterations does the loop need - is it possible, that it would exceed 16 bits integer?
With no data type identifier after the i, it is implied to be of the native Integer (the default). Therefore this i is expressed as an Integer, which makes it a 16-bit i.
So, I'd say it is the original developer had this habit of explicitly stating the variable type with &, and whether it was really needed there depends on the number of iterations that the For..Next loop has to support in this case.
Most likely it is either old code ported forward to VB6 from QBasic, etc. or else just a bad habit some individual programmer had from that era. While kind of sloppy its meaning should be obvious to a VB6 programmer, since it can be used with numeric literals in many cases too:
MsgBox &HFFFF
MsgBox &HFFFF&
These display different values because they are different values.
Yes it means Long but it often reflects somebody who fails to set the IDE option to auto-include Option Explicit in new modules when created.
Using symbolic notation (Integer - %, Long - &, Single - !, Double - #, String - $) is an excellent method for variable declaration and usage. It’s usage is consistent with "structured programming" and it’s a good alternative to Hungarian notation.
With Hungarian notation, one might define a string filename as “strFileName”, where the variable name is preceded by a lower case abbreviation of the variable type. The is contrary to another good programming practice of making all global variables begin with an upper case first letter and all local variables begin with a lower case. This helps the reader of your code instantly know the scope of a variable. Ie. firstName$ is a local string variable; LastName$ is a global string variable.
As with all programming, it’s good to follow conventions, ..whether you define your own conventions or somebody else’s conventions or industry conventions. Following no conventions is a very poor programming practice. Using symbolic notation is one type of naming convention.

Resources