检测变量的状态变化

huangapple go评论140阅读模式
英文:

Detecting State Change for a variable

问题

我正在编写一段代码,根据阈值检测状态变化。主要目标是只在状态变化时从函数中获取返回值。以下是我目前编写的代码。如果变量的状态没有改变,我们目前会在函数的返回值中返回一个空字符串""。有没有办法在状态不变时抑制返回值,而不是返回一个空字符串?

  1. func (f *stateChange) Exec(args []interface{}, _ api.FunctionContext) (interface{}, bool) {
  2. m1 := args[0]
  3. m2 := m1.([]interface{})
  4. valarray := []float64{}
  5. for _, v := range m2 {
  6. valarray = append(valarray, v.(float64))
  7. }
  8. firstval := valarray[0]
  9. secondval := valarray[1]
  10. message1 := "Medium Level Alarm"
  11. message2 := "High Level Alarm"
  12. message3 := "Normal Operation"
  13. message4 := "" //**空字符串**
  14. if secondval >= 50 && secondval < 100 && firstval < 50{
  15. return message1, true
  16. }
  17. if firstval >= 100 && secondval < 100 && secondval >= 50{
  18. return message1, true
  19. }
  20. if secondval >= 100 && firstval < 100{
  21. return message2, true
  22. }
  23. if firstval >= 50 && secondval < 50 {
  24. return message3, true
  25. }
  26. return message4, true //**需要抑制此输出中的空字符串**
  27. }
英文:

I am writing a code to detect state change based on a threshold value. Main goal is to get a return value from the function only when the state changes. Here is the code I have written so far. If the state of variable does not change currently we are returning &quot;&quot; empty string in the return value of the function. Is there a way that we can suppress the return value if the state does not changes, instead of returning &quot;&quot; (empty string)

`

  1. func (f *stateChange) Exec(args []interface{}, _ api.FunctionContext) (interface{}, bool) {
  2. m1 := args[0]
  3. m2 := m1.([]interface{})
  4. valarray := []float64{}
  5. for _, v := range m2 {
  6. valarray = append(valarray, v.(float64))
  7. }
  8. firstval := valarray[0]
  9. secondval := valarray[1]
  10. message1 := &quot;Medium Level Alarm&quot;
  11. message2 := &quot;High Level Alarm&quot;
  12. message3 := &quot;Normal Operation&quot;
  13. message4 := &quot;&quot; //**empty string**
  14. if secondval &gt;= 50 &amp;&amp; secondval &lt; 100 &amp;&amp; firstval &lt; 50{
  15. return message1, true
  16. }
  17. if firstval &gt;= 100 &amp;&amp; secondval &lt; 100 &amp;&amp; secondval &gt;= 50{
  18. return message1, true
  19. }
  20. if secondval &gt;= 100 &amp;&amp; firstval &lt; 100{
  21. return message2, true
  22. }
  23. if firstval &gt;= 50 &amp;&amp; secondval &lt; 50 {
  24. return message3, true
  25. }
  26. return message4, true //**empty string in return need to suppress this output**
  27. }

`

答案1

得分: 1

抑制此输出的最佳方法是使用 nil

  1. return nil, true
英文:

The best way to suppress this output is using nil.

  1. return nil, true

huangapple
  • 本文由 发表于 2021年7月2日 05:46:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/68217293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定