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 am trying to write a program using Go which perform tuple or variable unpacking as below in python
url = ('https://www.amazon.com/War-Art-Through-Creative-Battles' '/dp/1936891026/?keywords=war+of+art')
domain , *rest , isbn = url.split("/")[2:-1]
So I have written code as below using Go
package main
import (
"fmt"
"strings"
)
func main() {
var a string
a = ("https://www.amazon.com/War-Art-Through-Creative-Battles" +
"/dp/1936891026/?keywords=war+of+art") // dont use ' quotes
fmt.Println(a)
split_a := strings.Split(a, "/")
fmt.Println(split_a)
var rest []string
var domain string
var isbn string
domain, rest, isbn = split_a[2:-1]
}
and getting cannot assign 1 values to 3 variables compiler WrongAssignCount.
I understand the error as it reflects what I am trying to achieve, I am trying to find out the methods to achieve this and finally thought of checking with others. Any suggestions much appreciated.
Thank you.
This is just string manipulation, so no one right answer. Since your source is a
URL, I would say net/url is a good starting point:
package main
import (
"net/url"
"path"
)
func main() {
p, e := url.Parse(
"https://www.amazon.com/" +
"War-Art-Through-Creative-Battles/dp/1936891026/?keywords=war+of+art",
)
if e != nil {
panic(e)
}
rest, isbn := path.Split(path.Clean(p.Path))
println(
p.Host == "www.amazon.com",
rest == "/War-Art-Through-Creative-Battles/dp/",
isbn == "1936891026",
)
}
https://golang.org/pkg/net/url
Related
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
In my GoLang program which invokes a REST API, i need to collect the responses from different REST API's which return slices of pointers of the same struct.
I am attempting to concatenate the slices of pointers using append and i am getting error similar to what is shown below.
I think append does not support such an operation , is there any alternative to this ?
cannot use response (type []*string) as type *string in append
A go playground link for the problem ,i am trying to demonstrate is given here.
https://play.golang.org/p/lnzSd2kbht0
package main
import (
"fmt"
)
func main() {
var fruits []*string
response := GetStrings("Apple")
fruits = append(fruits, response...)
response = GetStrings("Banana")
fruits = append(fruits, response...)
response = GetStrings("Orange")
fruits = append(fruits, response...)
if fruits == nil || len(fruits) == 0 {
fmt.Printf("Nil Slice")
} else {
fmt.Printf("Non nil")
fmt.Printf("%v", fruits)
}
}
func GetStrings(input string) []*string {
var myslice []*string
myslice = append(myslice, &input)
return myslice
}
I cannot change the REST API or the function signature to return the slice of structs itself.
To append all elements of a slice to another slice, use:
resultSlice=append(slice1, slice2...)
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 am trying to pass a array with fix size into a string.join function. how can i pass array with define index into string.join function
program
package main
import(
"fmt"
"strings"
)
func main() {
var a [10]string
fmt.Println("emp:", a)
a[2] = "hello"
a[4] = "member of"
a[8] = "google"
str2 := strings.Join(a, " ")
fmt.Println(str2)
}
output
cannot use a (type [10]string) as type []string in argument to strings.Join
do i need to convet it in []string or any other solution is posible
strings.Join expects the argument to be slice. So, you need to convert the string array to slice like below
...
str2 := strings.Join(a[:], " ")
...
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 2 years ago.
Improve this question
I saw a piece of code used to print values passed in arguments:
package main
import "fmt"
import "os"
func main() {
for _, val := range os.Args[1:] {
fmt.Printf("%d %s \n", _ , val)
}
}
Original program had a note that _ holds index but was not printing it. When I tried to print index, I am getting below error:
./main.go:8:16: cannot use _ as value
What is the issue here?
_(underscore) in Golang is known as the Blank Identifier and it's value can't be used(it kind of doesn't hold any value).
Go doesn't allow you to have a unused variable therefore, original program used _ to drop the value and compile the program successfully. Use i instead of _ and run the program.
package main
import "fmt"
import "os"
func main() {
for i, val := range os.Args[1:] {
fmt.Printf("%d %s \n", i , val)
}
}
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 2 years ago.
Improve this question
coders. I'm completely newbie to Go and got a little bit confused about json.Unmarshal output:
package main
import (
"encoding/json"
"fmt"
)
func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`
var res []struct{}
err := json.Unmarshal([]byte(s), &res)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
Output:
[{} {} {}]
Why is it empty?
You can try it here: https://play.golang.org/p/yztOLJADIXx
If you want to unmarshal JSON objects without knowing their fields, use a map[string]interface{}:
package main
import (
"encoding/json"
"fmt"
)
func main() {
s := `[{"First":"James","Last":"Bond","Age":32,"Sayings":["Shaken, not stirred","Youth is no guarantee of innovation","In his majesty's royal service"]},{"First":"Miss","Last":"Moneypenny","Age":27,"Sayings":["James, it is soo good to see you","Would you like me to take care of that for you, James?","I would really prefer to be a secret agent myself."]},{"First":"M","Last":"Hmmmm","Age":54,"Sayings":["Oh, James. You didn't.","Dear God, what has James done now?","Can someone please tell me where James Bond is?"]}]`
var res []map[string]interface{}
err := json.Unmarshal([]byte(s), &res)
if err != nil {
fmt.Println(err)
}
fmt.Println(res)
}
Try it here: https://play.golang.org/p/iPlBgguE8Kk
However, if you know the names of the fields you're going to unmarshal, you should define the structure. In your case it would look like that:
type Person struct {
First string `json:"First"`
Last string `json:"Last"`
Age int `json:"Age"`
Sayings []string `json:"Sayings"`
}
Try this solution here: https://play.golang.org/p/jCrCteYTaIf
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 4 years ago.
Improve this question
I have a custom type named ProtectedCustomType and I don't want the variables within that to be set or get directly by the caller, rather want a Getter / Setter methods to do that.
Below is my ProtectedCustomType
package custom
import "fmt"
type ProtectedCustomType struct {
name string
age string
phoneNumber int
}
func (pct *ProtectedCustomType) SetAge (age string) {
pct.age=age
fmt.Println(pct.age)
}
func (pct *ProtectedCustomType) GetAge () string {
return pct.age
}
And here is my main function
package main
import (
"fmt"
"./custom"
)
var print =fmt.Println
func structCheck2() {
pct := custom.ProtectedCustomType{}
pct.SetAge("23")
age:=pct.GetAge
print (age)
}
func main() {
structCheck2()
}
I am expecting it to print 23, but it is printing as 0x48b950
This (your code) takes the pct instance's GetAge method and stores it in a variable:
age:=pct.GetAge
This calls the GetAge method and stores its return value in a variable:
age:=pct.GetAge()
Consider taking the Tour of Go and reading the Go Specification to get a basic understanding of Go syntax.