Cannot convert res.Data (type []twitterstream.rulesResponseValue) to type []byte

Solution for Cannot convert res.Data (type []twitterstream.rulesResponseValue) to type []byte
is Given Below:

I’ve been wasting many hours trying to pass data from this function to another, and I really need help at this point.

type Rules struct {
    Value string `json:"value"`
    Tag   string `json:"tag"`
    Id    string `json:"id"`
}

func getRules() {
    accessKey := os.Getenv("API_KEY")
    accessSecret := os.Getenv("API_SECRET_KEY")

    tok, err := twitterstream.NewTokenGenerator().SetApiKeyAndSecret(accessKey, accessSecret).RequestBearerToken()
    if err != nil {
        panic(err)
    }
    api := twitterstream.NewTwitterStream(tok.AccessToken)
    res, err := api.Rules.GetRules()

    if err != nil {
        panic(err)
    }

    if res.Errors != nil && len(res.Errors) > 0 {
        panic(fmt.Sprintf("Received an error from twiiter: %v", res.Errors))
    }


    bytes := []byte(res.Data)
    // this is the line, here 


    var rules []Rules
    json.Unmarshal(bytes, &rules)

    for l := range rules {
        fmt.Printf("Id = %v, Value = %v", rules[l].Id, rules[l].Value)
        fmt.Println()
    }

    fmt.Println(res.Data)
}

The error I’m getting is:
cannot convert res.Data (type []twitterstream.rulesResponseValue) to type []byte

Can somebody help me handle this data? I’m trying to convert the data into my own struct that I can return but it’s been one thing after another!

As long as your Rules type has the same underlying type as the rulesResponseValue type, you can use the conversion expression on the individual elements of the Data slice to directly convert an instance of type rulesResponseValue to an instance of the Rules type.

// I renamed Rules to Rule
type Rule struct {
    Value string `json:"value"`
    Tag   string `json:"tag"`
    Id    string `json:"id"`
}

func getRules() ([]Rule, error) {
    accessKey := os.Getenv("API_KEY")
    accessSecret := os.Getenv("API_SECRET_KEY")

    tok, err := twitterstream.NewTokenGenerator().SetApiKeyAndSecret(accessKey, accessSecret).RequestBearerToken()
    if err != nil {
        return nil, err
    }
    api := twitterstream.NewTwitterStream(tok.AccessToken)
    res, err := api.Rules.GetRules()
    if err != nil {
        return nil, err
    } else if res.Errors != nil && len(res.Errors) > 0 {
        return nil, fmt.Errorf("Received an error from twitter: %v", res.Errors)
    }

    rules := make([]Rule, len(res.Data))
    for i := range res.Data {
        rules[i] = Rule(res.Data[i]) // convert rulesResponseValue to Rule
    }

    return rules, nil
}

And you can then use that like this

func main() {
    rules, err := getRules()
    if err != nil {
        panic(err)
    }
    for _, r := range rules {
        fmt.Printf("Id = %v, Value = %vn", r.Id, r.Value)
    } 
}