dongqian6234 2018-11-05 12:27
浏览 41
已采纳

动态添加键值映射到结构

I am trying to figure out how I can add the key value pairs of a map[string]string into my prometheus.Labels struct.

If you've got experience with prometheus: I am trying to dynamically add labels and it's values.

labelsMap := make(map[string]string)
labelsMap["nodepool"] = "default"
labelsMap["zone"] = "europe-west"

// here I'd like to add my key / value pairs from my map
containerLabels := prometheus.Labels{
    "node":      "nodename",
    "container": "foo",
    "qos":       "bar",
}
requestedContainerCPUCoresGauge.With(containerLabels).Set(containerMetric.RequestedCPUCores)

My question:

How can I dynamically add the key/value pairs from my given map labelsMap in my containerLabels?

  • 写回答

1条回答 默认 最新

  • doutongwei4380 2018-11-05 12:30
    关注

    You may use a simple for range loop on labelsMap, and add each pair, e.g.:

    containerLabels := prometheus.Labels{}
    for k, v := range labelsMap {
        containerLabels[k] = v
    }
    

    Or since prometheus.Labels is just a simple map:

    type Labels map[string]string
    

    And if you don't want to modify the labelsMap afterwards, a simple type conversion also works:

    containerLabels := prometheus.Labels(labelsMap)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序