如何在Go中检查切片是否具有给定索引?

时间:2014-12-02 14:45:31

标签: go slice

我们可以使用地图轻松完成:

item, ok := myMap["index"]

但不是切片:

item, ok := mySlice[3] // panic!

感到惊讶的是之前没有被问过。也许我用Go切片在错误的心智模型上?

3 个答案:

答案 0 :(得分:21)

Go中没有稀疏切片,因此您只需检查长度:

if len(mySlice) > 3 {
    // ...
}

如果长度大于3,则您知道索引3以及之前的所有索引。

答案 1 :(得分:0)

if语句的使用是我不喜欢的,因为它使得阅读源代码变得更难,更优雅的方式是使用switch / case。 Switch / case在Go中非常多功能,所以在阅读了这篇文章中的所有答案之后,我想出了以下解决方案:

package main

import (
    "fmt"
)

func checkarg(data ...string) {
    for _, value := range data {
        fmt.Printf("<%v> ", value)
    }
    fmt.Println()
    switch len(data) {
    case 0:
        fmt.Println("No arguments at all!")
        fmt.Println("Missing <IP:port>")
        fallthrough
    case 1:
        fmt.Println("Missing <command>")
        fallthrough
    case 2:
        fmt.Println("Missing <key>")
        fallthrough
    case 3:
        fmt.Println("Missing <value>")
    case 4:
        fmt.Println("len = 4 (correct)")
    default:
        fmt.Println("Unknown length")
    }
}

func main() {
    checkarg("127.0.0.1:6379", "set", "Foo", "Bar", "test")
    fmt.Println()
    checkarg("127.0.0.1:6379", "set", "Foo", "Bar")
    fmt.Println()
    checkarg("127.0.0.1:6379", "set", "Foo")
    fmt.Println()
    checkarg("127.0.0.1:6379", "set")
    fmt.Println()
    checkarg("127.0.0.1:6379")
    fmt.Println()
    checkarg()
    fmt.Println()
}

输出:

<127.0.0.1:6379> <set> <Foo> <Bar> <test>
Unknown length

<127.0.0.1:6379> <set> <Foo> <Bar>
len = 4 (correct)

<127.0.0.1:6379> <set> <Foo>
Missing <value>

<127.0.0.1:6379> <set>
Missing <key>
Missing <value>

<127.0.0.1:6379>
Missing <command>
Missing <key>
Missing <value>


No arguments at all!
Missing <IP:port>
Missing <command>
Missing <key>
Missing <value>

它与您的问题不完全相同,但这只是为了让您了解如何解决它。

答案 2 :(得分:0)

检查切片中的索引

Future<?> Future = asyncTaskExecutor.submit(task)

检查地图中的键

public class A {

    
    private ThreadPoolTaskExecutor asyncTaskExecutor;

    public void asyncProcess(Map<String, String> requestData, String module, String action) {
        
        Task task = new Task(requestData, "task_name", module, action );
        try{
            asyncTaskExecutor.execute(task);
        }catch(TaskRejectedException e){
            logger.error("Email Notification Task Rejected, manually running task",e);
            task.run();
        }
    }
    
    
private class Task implements Runnable {
        

        
        private Map<String, String> requestData = new HashMap<String, String>();
        
        private NotificationRequest notificationRequest;
        
        private String Msgtype; 
        
        private String module;
        
        private String action;
        
        public NotificationTask(NotificationRequest notificationRequest, Map<String, String> requestData, String type){
            this.requestData = requestData;
            this.notificationRequest = notificationRequest;
            this.Msgtype = type;
        }
        
        public NotificationTask(Map<String, String> requestData, String type, String module, String action){
            this.requestData = requestData;
            this.Msgtype = type;
            this.module = module;
            this.action = action;
        }
    
        @Override
        public void run() {
            boolean exceptionOccured = false;
            try{
                if(Msgtype.equalsIgnoreCase("task_name")) {
                    System.out.println("completing task");
                }
            }catch(Exception e){
                logger.error( e.getMessage() );
                exceptionOccured = true;
            }
            
        }
    }
    
}