Sometimes i used to use if branch, sometimes AND operand.
But i feel they are both same.
What their different actually?
Any there example case which i must use that ONE only?
For example:
//Defining variable
a=2
b=3
if(a==2){
if(b==3){
println("OK");
}
}
It's equal with
if (a==2 && b==3){
println("OK");
}
You might use the first doubly-nested if condition when the inner if had an else branch, e.g.
if (a == 2) {
if (b == 3) {
println("OK");
}
else {
println("not OK")
}
}
If you don't have this requirement, then the second more concise version is probably what most would choose to use:
if (a == 2 && b == 3) {
println("OK");
}
Related
I've got a three component for loop that iterates over a Policies struct, which holds a list of Policy types, which is also a struct. However, in the for loop, the 'i++' is highlighted and apparently unreachable. I'm not sure why? Because when I run the application, it does actually execute the c.sendResultDialog function, so it is reachable, but I don't know why this error is showing up.
for i := 0; i < len(policies.Policies); i++ {
if strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyName) || strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyId) {
c.sendResultDialog(TestFoundPolicy, c.name, policies.Policies[i].PolicyId, policies.Policies[i].PolicyDescription)
return true
} else {
c.sendResultDialog(PolicyNotFound, c.name)
return false
}
}
This is hard to tell without a full example (no idea what sendResultDialog is doing). But the error is likely due to the fact that you're returning from within a loop, you can try something like this instead:
policyFound := false
for i := 0; i < len(policies.Policies); i++ {
if strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyName) || strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyId) {
c.sendResultDialog(TestFoundPolicy, c.name, policies.Policies[i].PolicyId, policies.Policies[i].PolicyDescription)
policyFound = true
break // remove this if you want to call sendResultDialog for all entries and not just the first one
}
}
if !policyFound {
c.sendResultDialog(PolicyNotFound, c.name)
}
return policyFound
Since, you call return inside the for loop, you are not iterating over all the slice values.
You would probably do this
policy_found := false
for i := 0; i < len(policies.Policies); i++ {
if strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyName) || strings.ToLower(c.name) == strings.ToLower(policies.Policies[i].PolicyId) {
c.sendResultDialog(TestFoundPolicy, c.name, policies.Policies[i].PolicyId, policies.Policies[i].PolicyDescription)
policy_found = true
}
}
if !policy_found {
c.sendResultDialog(PolicyNotFound, c.name)
}
return policy_found
this should fix your bug
My golint returns this error message but i don't really understand what it means.
As in title:
return statements should not be cuddled if block has more than two lines (wsl)
my code is this:
func validateCountry(product models.Product, countries []models.Country) bool {
if !product.CountryCode.Valid {
return true
}
for _, country := range countries {
if country.Code == product.CountryCode.String {
return !country.Enabled && country.Deprecated
}
}
return false
}
What the linter does not like seems to be the last return false.
I'm very confused, i didn't setup the linter in this codebase, and i don't really know how to either skip this rules or how to fix it.
This error means that, in your case, you need to put a blank line before any next return statement:
[empty line] <-- need this
return true
...
[empty line] <-- need this
return !country.Enabled && country.Deprecated
should not be cuddled means there must be no code lines near the return statement.
I have an if statement in Go which looks like this:
if level & 1 {
// do something
} else {
// do something else
}
The level variable in my cause is of type uint. But when I do bitwise AND with 1, the result is not a boolean. This is a valid syntax for C, but apparently it doesn't work in Go. Any idea how to work around this?
If statements in Go must have type of bool, which you can achieve by using a comparison operator, the result of which is a bool:
if level&1 != 0 {
// do something
} else {
// do something else
}
I'm a golang neophyte and I've come across a rather interesting control structure which doesn't follow the classical imperative for-loop construct. I've been unable to locate on documentation on the structure either. The following is the code in question:
for {
// read each incoming message
m, err := getMessage(ws)
if err != nil {
log.Fatal(err)
}
// see if we're mentioned
if m.Type == "message" && strings.HasPrefix(m.Text, "<#"+id+">") {
// if so try to parse if
ans := lookup(session, m.Text)
if len(ans)>0 {
// looks good, get the quote and reply with the result
go func(m Message) {
for _, def := range ans {
if len(def[1]) > 0 {
m.Text = "*" + def[0] + " " + def[1] + "*: " + def[2]
} else {
m.Text = "*" + def[0] + "*: " + def[2]
}
postMessage(ws, m)
}
}(m)
// NOTE: the Message object is copied, this is intentional
} else {
// huh?
m.Text = fmt.Sprintf("sorry, that does not compute\n")
postMessage(ws, m)
}
}
}
Does the loop construct just loop forever or is there an eventing system binding behind the scenes?
The Go Programming Language Specification
For statements
A "for" statement specifies repeated execution of a block. The
iteration is controlled by a condition, a "for" clause, or a "range"
clause.
ForStmt = "for" [ Condition | ForClause | RangeClause ] Block .
Condition = Expression .
In its simplest form, a "for" statement specifies the repeated
execution of a block as long as a boolean condition evaluates to true.
The condition is evaluated before each iteration. If the condition is
absent, it is equivalent to the boolean value true.
If the condition is absent, for example, for { ... }, it is equivalent to the boolean value true, for example for true { ... }. It is sometimes referred to as an infinite loop. Therefore, you will need another mechanism, such as break or return, to terminate the loop.
The documentation for the for statement is the The Go Programming Language Specification.
for without any additional statements is basically the same as while (true) in other languages, an infinite loop.
I'm making my way through The Swift Programming Language book, but I'm stuck on an experiment.
I'm given this code:
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "Ace"
case .Jack:
return "Jack"
case .Queen:
return "Queen"
case .King:
return "King"
default:
return String(self.toRaw())
}
}
}
For the experiment, I have to "Write a function that compares two Rank values by comparing their raw values.
I had a go:
func rankCompare(first: String, second: String) -> String {
let firstRank = Rank.first
}
But I ended up with errors because I don't know how to pass Enum values.
Can someone help?
Enum values can be passed just like other types. The following function is part of the Rank enum and compares one Rank to another.
func compareToOther(other:Rank) -> Bool { // other is of type Rank
return self.toRaw() == other.toRaw()
}
Here is a screenshot of the quick implementation and usage.
You can pass enums by just passing the enum name:
// someRank is a Rank enum value
func myFunction (someRank: Rank) -> () {
}
And then you can just call it:
myFunction(Rank.Ace)
I am also a beginner, but this is how I worked throughout the experiment. First I added this;
func compareTwoCards(card1: Rank, card2: Rank) -> String {
if card1.toRaw() == card2.toRaw() {
return "Cards are equal"
} else {
if card1.toRaw() > card2.toRaw() {
return "Card1 is greater"
} else {
return "Card2 is greater"
}
} }
Then I created two Rank objects
let ace = Rank.Ace
let queen = Rank.Queen
Finally, I called it three different ways to test it;
compareTwoCardsTake2(ace, queen)
compareTwoCardsTake2(queen, ace)
compareTwoCardsTake2(ace, ace)
Can some one with more experience please reply if there is a better/more elegant way of performing the compare?
I solved it like this:
func rankCompare(first: Rank, second: Rank) -> String {
if(first.rawValue > second.rawValue) {
return "\(first.simpleDescription()) beats \(second.simpleDescription())."
}
else if second.rawValue > first.rawValue {
return "\(second.simpleDescription()) beats \(first.simpleDescription())."
}
else {
return "\(first.simpleDescription()) equals \(second.simpleDescription())."
}
}
let king = Rank.King
let queen = Rank.Queen
let seven = Rank.Seven
rankCompare(king, queen)
rankCompare(seven, king)
rankCompare(queen, queen)
Use .rawValue for doing the comparisons and .simpleDescription() for writing out your answer.
This code can be used to determine if two enumeration values are equal or not. .toRaw() is obsolete, so .rawValue must be used to obtain the raw value for comparison. An edited version of this function (to make a full comparison with type string information, not just "true" or "false") should be used to complete the exercise. Hint For Editing: this function is of type Bool.
func compareRanks(rankA: Rank, rankB: Rank) -> Bool {
return rankA.rawValue == rankB.rawValue
}
To see the code and contributors that made this answer possible, please see the question: Explanation of The Swift Programming Language Enumerations Experiment