python "return none" equivalence [closed] - go

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
How to achieve same thing as the following python code in Go without for loop?
def test(i):
if i == 0:
return None
else:
print(i)
return test(i - 1)

The python function never returns a value:
func test(i int) {
if i==0 {
return
}
fmt.Println(i)
test(i-1)
}

Use a second return value to indicate that the function returned a valid value:
func test(i int) (int, bool) {
if i == 0 {
return 0, false
}
fmt.Println(i)
return test(i - 1)
}
In this specific example, the return value to the top-level caller is always 0, false. Given this, the return value is not needed.
func test(i int) {
if i == 0 {
return
}
fmt.Println(i)
test(i - 1)
}

Related

How can I change the variable inside the if statement of switch statement in Golang? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
I am a newbie in Golang and now I have a requirement to change a value inside the if statement.
Here is my dummy code.
package main
func main() {
a := "hi"
pull_enable := true
switch a {
case "hi":
image_list := []float32{
0,
2,
}
for image:=0; image<len(image_list); image++{
if image == 0 {
pull_enable = true
break
}
}
}
}
I define a variable pull_enable outside of switch statement, and I want to change this variable value in the if statement, but when I built it, it encountered an issue below.
# command-line-arguments
pull_enable declared but not used
I am wondering how I can fix this issue. Is there any idea?
package main
import "fmt"
func main() {
a := "hi"
pullEnable := true
switch a {
case "hi":
image_list := []float32{
0,
2,
}
for image := 0; image < len(image_list); image++ {
if image == 0 {
pullEnable = true
break
}
}
}
fmt.Println(pullEnable)
}

How func ContainsAny() works in Go? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Considering the following code
func main() {
arg := os.Args
if len(arg[1]) != 1 || len(arg) != 2 {
fmt.Println("Give me a letter.")
return
}
if (strings.IndexAny(arg[1], "yw") == 0) {
fmt.Printf("%q is a semivowel.\n", arg[1])
} else if strings.IndexAny(arg[1], "aeiou") == 0 {
fmt.Printf("%q is a vowel.\n", arg[1])
} else {
fmt.Printf("%q is a consonant.\n", arg[1])
}
}
and more specifically this section:
if (strings.IndexAny(arg[1], "yw") == 0) {
fmt.Printf("%q is a semivowel.\n", arg[1])
} else if strings.IndexAny(arg[1], "aeiou") == 0 {
fmt.Printf("%q is a vowel.\n", arg[1])
} else {
fmt.Printf("%q is a consonant.\n", arg[1])
}
I could not understand why it only worked when I informed the bool equal to zero but not when equal to one. (According to the official documentation https://pkg.go.dev/strings#ContainsAny shouldn't it be equal to 1, as in true?)
According to the documentation, the function you used should return an integer:
package strings // import "strings"
func IndexAny(s, chars string) int
IndexAny returns the index of the first instance of any Unicode code point
from chars in s, or -1 if no Unicode code point from chars is present in s.
and strings.ContainsAny returns a boolean
package strings // import "strings"
func ContainsAny(s, chars string) bool
ContainsAny reports whether any Unicode code points in chars are within s.
You can read the documentation from a terminal running the command:
go doc strings.IndexAny # or any go function or package you want

How to sort a slice of string [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm trying to sort a slice of string, which look like "hour:minute:second".
func main() {
rows := []string{
"1:2:8",
"1:2:5",
"1:2:6",
}
sort.SliceStable(rows, func(i, j int) bool {
var hour_i, min_i, sec_i int
var hour_j, min_j, sec_j int
fmt.Sscanf(rows[i], "%d:%d:%d", &hour_i, &min_i, &sec_i)
fmt.Sscanf(rows[j], "%d:%d:%d", &hour_j, &min_j, &sec_j)
return hour_i < hour_j && min_i < min_j && sec_i < sec_j
})
for _, x := range rows {
fmt.Println(x)
}
}
But the result is same to the input, not sorted. Why is that?
You need to compare each item separately
sort.SliceStable(rows, func(i, j int) bool {
var hour_i, min_i, sec_i int
var hour_j, min_j, sec_j int
fmt.Sscanf(rows[i], "%d:%d:%d", &hour_i, &min_i, &sec_i)
fmt.Sscanf(rows[j], "%d:%d:%d", &hour_j, &min_j, &sec_j)
if hour_i < hour_j {
return true
}
if min_i < min_j {
return true
}
return sec_i < sec_j
})
You can sort your slice using simple sort.Strings() method from sort package,modifying your code and sorting it with the same logic as follows:
package main
import (
"fmt"
"sort"
)
func main() {
rows := []string{
"1:2:8",
"1:2:5",
"1:2:6",
"2:0:7",
"1:0:6",
"2:0:5",
}
sort.Strings(rows)
for _, val := range rows {
fmt.Println(val)
}
}
Output :
1:0:6
1:2:5
1:2:6
1:2:8
2:0:5
2:0:7

How can I assign a function to a variable without executing it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
When I try to assign a map key to a function it executes the function. How can I do this without executing the function?
var myslice []int
myslice = append(myslice, 1)
func RemoveIndex(s []string, index int) []string {
return append(s[:index], s[index+1:]...)
}
a["removeIndex"] = removeIndex(myslice, 0)
Just assign the function to the map[string]func([]string,int)[]string's key
func RemoveIndex(s []string, index int) []string {
return append(s[:index], s[index+1:]...)
}
a["removeIndex"] = RemoveIndex
rifn := a["removeIndex"]
rifn(myslice, 0)

Convert map values to plain strings without brackets? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a map string that looks like this
map[first:[hello] second:[world]]
The problem is that when I iterate over it and return the values they return [hello] [world] and I want them to just return hello world
// currentMap is of type map[interface{}]interface{} originally
newStringMap := make(map[string]interface{})
for k, v := range currentMap {
newStringMap[k.(string)] = v
}
return newStringMap
How can this be done?
From the below information provided by you:
when I iterate over it and return the values they return [hello] [world]
It seems that your currentMap actually stores string slices []string as values, behind the interface{} type. Assuming that above line means that you see this when printing the map using fmt.Println(), or similar functions.
map[first:[hello] second:[world]]
Here's a possible reproduction & solution of your problem::
package main
import (
"fmt"
)
func main() {
currentMap := make(map[interface{}]interface{})
currentMap["first"] = []string{"hello"}
currentMap["second"] = []string{"world"}
newStringMap := make(map[string]interface{})
fmt.Println("Problem:")
fmt.Printf("%v\n", currentMap)
fmt.Println("\nSolution:")
for k, v := range currentMap {
lst, ok := v.([]string)
//fmt.Println(lst, ok)
if ok && len(lst) > 0 {
newStringMap[k.(string)] = v.([]string)[0]
} else {
newStringMap[k.(string)] = nil
}
}
fmt.Printf("%v\n", newStringMap)
}
Which outputs to:
Problem:
map[first:[hello] second:[world]]
Solution:
map[first:hello second:world]
Try it here
https://play.golang.org/p/5XAA3m6MDX_b
It's not necessary that the content stored in currentMap is always of similar type. (if it is, then why would interface{} ever be used). Which means, don't forget your error-checking. I have tried to cover the same. You may need to add some more, based on the possible actual types in the map, similar to this section:
if ok && len(lst) > 0 {
newStringMap[k.(string)] = v.([]string)[0]
} else {
newStringMap[k.(string)] = nil
}

Resources