Вставьте в вывод все один два три идентификатора продукта, которые начинаются с цифры «1».

# #go

Вопрос:

Я новичок в этом деле. Как мне вставить в вывод все один два три идентификатора продукта, которые начинаются с цифры «1»

 package main

import (
    "fmt"
)

func main() {
    var output []string
    // 1) Insert into output all one   two   three product IDs that start with the digit "1"

    fmt.Println(output)

}

func GetOneProductIDs() (out []string) {
    for i := 0; i < 100; i  = 10 {
        out = append(out, fmt.Sprintf("%d_%s", i, "one"))
    }
    return out
}

func GetIwoProductIDs() (out []string) {
    for i := 0; i < 100; i  = 5 {
        out = append(out, fmt.Sprintf("%d_%s", i, "two"))
    }
    return out
}

func GetThreeProductIDs() (out []string) {
    for i := 0; i < 100; i  = 2 {
        out = append(out, fmt.Sprintf("%d_%s", i, "three"))
    }
    return out

}
 

https://play.golang.org/p/ftdSMJiSfq_D

Ответ №1:

У меня есть довольно примитивное и простое решение для вас, но оно отлично работает:

 package main

import (
    "fmt"
    "strings"
)

func main() {

    var output []string
    // 1) Insert into output all one   two   three product IDs that start with the digit "1"
    for _, res := range GetOneProductIDs() {
        if strings.HasPrefix(res, "1") {
            output = append(output, res)
        }
    }
    for _, res := range GetIwoProductIDs() {
        if strings.HasPrefix(res, "1") {
            output = append(output, res)
        }
    }
    for _, res := range GetThreeProductIDs() {
        if strings.HasPrefix(res, "1") {
            output = append(output, res)
        }
    }
    fmt.Println(output)

}

func GetOneProductIDs() (out []string) {
    for i := 0; i < 100; i  = 10 {
        out = append(out, fmt.Sprintf("%d_%s", i, "one"))
    }
    return out
}

func GetIwoProductIDs() (out []string) {
    for i := 0; i < 100; i  = 5 {
        out = append(out, fmt.Sprintf("%d_%s", i, "two"))
    }
    return out
}

func GetThreeProductIDs() (out []string) {
    for i := 0; i < 100; i  = 2 {
        out = append(out, fmt.Sprintf("%d_%s", i, "three"))
    }
    return out
}
 

https://play.golang.org/p/RwDFEMJ-5Je