0

I’ve the following code which needs to get int value and add it to a string with string suffix. E.g.

At start I'm getting this

"fds data "

After the if statement it should like this

"fds data 10 M"

This is the code:

ltrCfg := "fds data "
if len(cfg.ltrSharedDicts) > 0 {
    ltrCfg += strconv.Itoa(cfg.ltrSharedDicts["c_data"])
    ltrCfg += "M"
} else {
    ltrCfg += "10M"
}
out = append(out, ltrCfg)

ltrCert := “fds data "
if len(cfg.ltrSharedDicts) > 0 {
    ltrCert += strconv.Itoa(cfg.ltrSharedDicts["d_data"])
    ltrCert += "M"
} else {
    ltrCert += “20M"
}
out = append(out, ltrCert)

The code is working but I wonder for the first fork of the if statement

if len(cfg.ltrSharedDicts) > 0 {
    ltrCfg += strconv.Itoa(cfg.ltrSharedDicts["c_data"])
    ltrCfg += "M"

Is there a better way to achieve it?

2
  • 2
    fmt.Sprintf will be much simpler, no? Commented Jun 23, 2019 at 10:50
  • 1
    I'd use fmt.Sprintf to do this kind of thing
    – Vorsprung
    Commented Jun 23, 2019 at 13:35

1 Answer 1

1

For readability, I would write:

cd, ok := cfg.ltrSharedDicts["c_data"]
if !ok {
    cd = 10
}
out = append(out, fmt.Sprintf("fds data %dM", cd))
2
  • Thanks, sorry but I didnt understand the if ? sometimes it should get hardcoded value, you can see that on the else..
    – NSS
    Commented Jun 23, 2019 at 11:43
  • 1
    @NinaS: If the map doesn't contain a value for "c_data" (!ok) then use the default value (10). "The value of ok is true if the key x is present in the map, and false otherwise.": golang.org/ref/spec#Index_expressions
    – peterSO
    Commented Jun 23, 2019 at 11:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.